Skip to content

Instantly share code, notes, and snippets.

@altrive
Created January 25, 2014 23:48
Show Gist options
  • Select an option

  • Save altrive/8625656 to your computer and use it in GitHub Desktop.

Select an option

Save altrive/8625656 to your computer and use it in GitHub Desktop.
Sample code to execute ping in parallel
function Main
{
$ipAddresses = 1..254 | foreach { "192.168.0.$_" }
#$ipAddresses | Invoke-ParallelPing | Out-GridView
Invoke-ParallelPing -ComputerName $ipAddresses | Out-GridView
}
function Invoke-ParallelPing
{
[CmdletBinding()]
param (
[Parameter(Mandatory, ValueFromPipeline)]
[string[]] $ComputerName,
[int] $TimeoutMilliseconds = 1000,
[int] $PingDataSize = 32
)
begin
{
$ErrorActionPreference = "Stop"
$pingOptions = New-Object Net.NetworkInformation.PingOptions(64, $false)
$pingData = New-Object byte[]($PingDataSize)
$tasks = @()
}
process
{
$ComputerName | foreach {
$targetName = $_
$ping = New-Object Net.NetworkInformation.Ping
$task = $ping.SendPingAsync($targetName, $TimeoutMilliseconds, $pingData, $pingOptions)
$tasks += [pscustomobject] @{
ComputerName = $targetName
Task = $task
PingObject = $ping
}
}
}
end
{
[Threading.Tasks.Task]::WaitAll($tasks.Task)
foreach ($task in $tasks)
{
[Net.NetworkInformation.PingReply] $result = $task.Task.Result
[pscustomobject] @{
Id = $task.Task.Id
TargetName = $task.ComputerName
IsSuccess = $result.Status -eq [Net.NetworkInformation.IPStatus]::Success
Status = $result.Status
RoundtripTime = $result.RoundtripTime
}
}
foreach ($task in $tasks)
{
#TODO:Should be disposed in $task.ContinueWith({}) block
$task.PingObject.Dispose()
$task.Task.Dispose()
}
}
}
. Main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment