Created
November 7, 2021 01:14
-
-
Save MartinMiles/062876422a8ae6fc107b894d27dd9d46 to your computer and use it in GitHub Desktop.
A multithreaded network ping written on PwerShell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Param ( | |
[string[]]$Address = $(1..20 | %{"192.168.1.$_"}), | |
[int]$Threads = 5 | |
) | |
write-host "Distributing addresses around jobs" | |
$JobAddresses = @{} | |
$CurJob = 0 | |
$CurAddress = 0 | |
while ($CurAddress -lt $Address.count) | |
{ | |
$JobAddresses[$CurJob] += @($Address[$CurAddress]) | |
$CurAddress++ | |
if ($CurJob -eq $Threads -1) | |
{ | |
$CurJob = 0 | |
} | |
else | |
{ | |
$CurJob++ | |
} | |
} | |
$Jobs = @() | |
foreach ($n in 0 .. ($Threads-1)) | |
{ | |
Write-host "Starting job $n, for addresses $($JobAddresses[$n])" | |
$Jobs += Start-Job -ArgumentList $JobAddresses[$n] -ScriptBlock { | |
$ping = new-object System.Net.NetworkInformation.Ping | |
Foreach ($Ip in $Args) | |
{ | |
trap { | |
new-object psobject -Property { | |
Status = "Error: $_" | |
Address = $Ip | |
RoundtripTime = 0 | |
} | |
Continue | |
} | |
$ping.send($Ip,100) | select ` | |
@{name="Status"; expression={$_.Status.ToString()}}, | |
@{name = "Address"; expression={$Ip}}, RoundtripTime | |
} | |
} | |
} | |
write-host "Waiting for jobs" | |
$ReceivedJobs = 0 | |
while ($ReceivedJobs -le $Jobs.Count) | |
{ | |
foreach ($CompletedJob in ($Jobs | where {$_.State -eq "Completed"})) | |
{ | |
Receive-Job $CompletedJob | select status, address, roundtriptime | |
$ReceivedJobs ++ | |
sleep 1 | |
} | |
} | |
Remove-Job $Jobs | |
write-host "Done." | |
# Script has 2 arguments: | |
# - Threads - number of threads | |
# - Address - an array of ip addresses. You can use this: 1..254 | ${"192.168.1.$_"} | |
# Call example: | |
# .\ThreadPing.ps1 -Address (1..20|%{"192.168.1.$_"}) -threads 5 | |
# .\ThreadPing.ps1 -Address (1..254|%{"192.168.1.$_"}) -threads 20 | where {$_.status -eq "success"} | |
# | |
# $IPs = 1..3 | %{$s=$_; 1..254 | %{"192.168.$s.$_"}} | |
# .\ThreadPing.ps1 -Address $Ips -threads 20 | where {$_.status -eq "success"} | Select -expandproperty Address |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment