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

Python Module: Datetime

Datetime Programs often include dates and time to perform interactive greetings, calculate age, stamping backups,…

PowerShell: Get Available RAM Slots

# getRamSlotsAvailable.ps1 $computername=$env:computername function getRamSlotsAvailable{ param($computername=$env:computername) write-host "Computer name: $computerName" $slots = Get-WmiObject -Class "win32_PhysicalMemoryArray"…

How to Import Files Into a Docker Container

1. Use SCP to copy files to the remote server while logged onto the local…