Posted On May 26, 2020

PowerShell: How to Create Multiple Arrays or Columns from an Array

kimconnect 0 comments
blog.KimConnect.com >> Codes >> PowerShell: How to Create Multiple Arrays or Columns from an Array
# This snippets scans the localhost for common ports and outputs 4 arrays

$limitPorts=10000                                                                 
$netstat=netstat -aon
$commonPortsInUse=$netstat|%{
                            [void]($_ -match "\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\:(\d{1,5})");
                            try{[int]$port=$matches[1]}catch{$port=0}
                            if($port -gt 0 -and $port -lt $limitPorts){$port}
                            }|select-object -Unique|sort

function splitArray($arr,$fragments){
[int]$columns=$fragments
[int]$breakPoint=1;
[int]$elementsPerColumn=$arr.count/[int]$columns
$result=@()
for ($i=1;$i -le $columns;$i++){
        $breakPoint=$elementsPerColumn*$i
        if($i -eq 1){
        $start=0;
        $stop=$breakPoint-1;
            }elseif($i -eq $columns){
                $start=$breakPoint-$elementsPerColumn;
                $stop=$arr.count-1;
                }else{
                $start=$breakPoint-$elementsPerColumn;
                $stop=$breakPoint-1;
                }                                                                         
        #write-host "StartIndex: $start StopIndex: $stop"
        #write-host $arr[$start..$stop]
$result+=,@($commonPortsInUse[$start..$stop])
        }
return $result
}

function displayArrayAsColumns($arr,$columns){
return $arr|format-wide {$_} -Column $columns -force
}

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Post

Last Logon Dates of List of AD Accounts

import-module activedirectory$output=""Get-Content C:\Users\kimconnect\Desktop\targetAccounts.txt | Foreach-Object -Process{ #  cast an array object as string before using…

PowerShell: Function to Confirm Certain Contents

It's always a good idea to receive user confirmations prior on proceeding to making important…

PowerShell: DHCP Server Scope Options Editing

Occasionally, internal DNS server changes as machines are refreshed and/or decommissioned. DHCP servers should also…