Home > Blockchain >  PowerShell Multi-Threading
PowerShell Multi-Threading

Time:10-17

I'm going to develop an asset discovery using ping. I need to ping multiple networks simultaneously, so the discovery speed would grow. In order to do that, I define a hash table as the following, containing destination networks. So, how can I ping multiple network simultaneously?

Please take a look at a snippet of my code:

 $Hosts = @{}
 $Time = Get-Date
 $Networks = @{
    Network_X = 1..254 | ForEach-Object{ "192.168.50.$_"}
    Network_Y = 1..254 | ForEach-Object{ "192.168.63.$_"}
    Network_Z = 1..254 | ForEach-Object{ "192.168.65.$_"}
 }

I've failed using "ForEach-Object" or "Foreach".

CodePudding user response:

You can use Ping.SendPingAsync() to initiate a ping asynchronously:

$PingTasks = foreach($network in $Networks.GetEnumerator()) {
  foreach($ip in $network.Value){
    # for each IP in each network, create a new object with both details   an async ping task
    [pscustomobject]@{
      Network = $network.Name
      IP      = $ip
      Request = [System.Net.NetworkInformation.Ping]::new().SendPingAsync($IP)
    }
  }
}

# Wait for all tasks to finish
[System.Threading.Tasks.Task]::WaitAll($PingTasks.Request)

# Gather results
foreach($task in $PingTasks){
  if($task.Request.Result.Status -eq 'Success'){
    # Extract Network   IP from the hosts that responded to our ping
    $Hosts[$task.IP] = $task |Select-Object Network,IP
  }
}

$Hosts will now contain an entry for each successfully ping'ed IP, with the network name attached.

  • Related