Skip to content

Instantly share code, notes, and snippets.

@sub314xxl
Created October 18, 2016 19:56
Show Gist options
  • Save sub314xxl/a655303ed45c5fadb57fc32675dad6b1 to your computer and use it in GitHub Desktop.
Save sub314xxl/a655303ed45c5fadb57fc32675dad6b1 to your computer and use it in GitHub Desktop.
multithreading network scanner
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."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment