Search code examples
powershellpingjobs

PowerShell quickly Ping Subnet with Jobs


The following function will ping my subnet with PingRange 1 254 to check IP's:

function PingRange ($from, $to) {
    $from..$to | % {"192.168.0.$($_): $(Test-Connection -BufferSize 2 -TTL 5 -ComputerName 192.168.0.$($_ ) -quiet -count 1)"}
}

However, this is slow, so I was wondering if it's possible to ping them all concurrently, then collect the results. I guess that this would mean:

  1. Using Start-Job on each Test-Connection (which I can do, that part is easy).

  2. Waiting for all to complete.

  3. Collecting only the ping success results and sorting them.

    function PingRange $from $to { $from..$to | % {Start-Job { "192.168.0.$($_): $(Test-Connection -BufferSize 2 -TTL 5 -ComputerName 192.168.0.$($_ ) -quiet -count 1)"} } Wait-Job *some test to check if all jobs are complete* Receive-Job some way to get each result, discard all failures, then sort and output to screen }

Is there a shorthand way to do a Wait-Job that will just wait for all spawned jobs to complete?

Receiving the information also seems tricky, and when I try it, I invariable get nothing back from Receive-Job (or a nasty error usually). Hopefully someone more expert on PowerShell Jobs knows how to grab these results easily?


Solution

  • Preface:

    The answer below focuses on command-agnostic ways to achieve concurrency (not just with jobs).


    In PowerShell 7, you can use ForEach-Object -Parallel, which can greatly simplify your function, by running your commands in parallel, using different threads:

    function PingRange ($from, $to) {
      $from..$to | ForEach-Object -Parallel {
        "192.168.0.$_`: $(Test-Connection -BufferSize 2 -TTL 5 -ComputerName 192.168.0.$_ -quiet -count 1)"
      } -ThrottleLimit ($to - $from + 1) 2>$null -ErrorVariable err | Sort-Object
    }
    
    • -ThrottleLimit defaults to 5, which means that up to 5 commands run in parallel, which additional ones queued until one threads in the pool become available again, as previous commands finish.

      • Here, I've chosen to allow all threads to run in parallel, but you'll have to test if that works in practice - it may work for network-bound tasks such as here, but it's not right choice for CPU-bound tasks; see this blog post for guidance.
    • 2>$null silences error output, but -ErrorVariable err collects any errors in variable $err for later inspection:

      • Note: As of v7.0, only 2>$null works for silencing errors; the common -ErrorAction parameter is not supported (and neither are -WarningAction, -InformationAction, -PipelineVariable); note that 2>$null can trigger a script-terminating error if $ErrorActionPreference = 'Stop' happens to be in effect.
    • Output from the threads will arrive in no guaranteed order, but will print as it arrives.

      • Given that your want sorted output anyway, that is not a problem here.
      • If you do need the output in input order, use the -AsJob parameter, use the resulting job object with Wait-Job to wait for all threads to finish, at which point you can call Receive-Job to receive all the outputs in input order.

    In Windows PowerShell, you do need jobs for concurrency, but it's better to use Start-ThreadJob than Start-Job, because thread jobs have much less overheads than the standard background jobs, which are child-process-based.
    Jobs of either type can be managed with the same set of other job-related cmdlets, such as Receive-Job, shown below.

    Note: The implementing ThreadJob module ships with PowerShell 7; in Windows PowerShell you can install it on demand; e.g.: Install-Module ThreadJob -Scope CurrentUser.

    function PingRange ($from, $to) {
      $from..$to | ForEach-Object {
        Start-ThreadJob -ThrottleLimit ($to - $from + 1) { 
          "192.168.0.$using:_`: $(Test-Connection -BufferSize 2 -TTL 5 -ComputerName 192.168.0.$using:_ -quiet -count 1)" 
        }
      } | Receive-Job -Wait -AutoRemove -ErrorAction SilentlyContinue -ErrorVariable err |
          Sort-Object 
    }
    

    Note the need for $using:_ in order to reference the enclosing ForEach-Object script block's $_ variable.

    While Start-ThreadJob uses threads (runspaces) to run its jobs, the resulting job objects can be managed with the standard job cmdlets, namely Wait-Job, Receive-Job and Remove-Job.


    Advantages of using Start-ThreadJob over Start-Job:

    • Start-ThreadJob uses threads (separate in-process PowerShell runspaces via the PowerShell SDK) for concurrency rather than the child processes Start-Job uses. Thread-based concurrency is much faster and less resource-intensive.

      • See this answer for an example of the performance gains that Start-ThreadJob brings.
    • The output from thread jobs retain their original type.

      • By contrast, in Start-Job jobs input and output must cross process boundaries, necessitating the same kind of XML-based serialization and deserialization that is used in PowerShell remoting, where type fidelity is lost except for a few known types: see this answer.

    The only - largely hypothetical - downside of Start-ThreadJob is that a crashing thread could crash the entire process, but note even a script-terminating error created with Throw only terminates the thread (runspace) at hand, not the caller.

    In short: use Start-Job only if you need full process isolation; that is, if you need to ensure the following:

    • A crashing job must not crash the caller.

    • A job should not see .NET types loaded into the caller's session.

    • A job should not be able to modify the caller's environment variables (in jobs of both types the caller's environment variable values are present, but in the case of background jobs they are copies).

    Note that in both Start-ThreadJob and Start-Job jobs, the jobs do not see the caller's state in terms of:

    • Variables, functions, aliases, or PSv5+ custom classes added to the caller's session, either interactively or via a $PROFILE file - jobs do not load $PROFILE files.

      • However, thread jobs do see .NET classes (types) loaded into the caller's session, and, unlike regular jobs, they not only see the values of the caller's environment variables, but can also modify them.

      • Both cmdlets support passing the values of regular variables from the caller's scope, via the $using: scope.

    • In PowerShell 6-, the initial current directory (filesystem location) for jobs was not the same as the caller's; fortunately, this is fixed in v7+; once started, jobs maintain their own current location and changing it does not affect the caller.