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

PowerShell: Invoke-Command to Add A Host Record on DNS Server

# DNS Host Record Information $aRecord="superman" $recordIP='192.168.0.256' $zoneName='kimconnect.com' $dnsServer='dc01.intranet.kimconnect.com' # Admin Credential $adminUsername='DoeManeAdmin' $adminPassword='WhatPassword?' $adminCredential=New-Object…

How to Disable WordPress Auto Wrap Function ‘wpautp’

Update: the current version of WordPress has rendered these methods ineffective. I'll update this post…

PowerShell: Get Executable Version and File Location

# Quick method to obtain computernames of all nodes in a cluster and adjoin result…