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 *