How To Invoke Functions as Background Jobs

Invoke-Command, Start-Job, Multi-Tasking is what good coders should aspire toward. Here, we’re looking at some useful methods to make our programs more efficient.

# Demo 2: This is a more advanced technique to perform simultaneous tasking on multiple computers by invoking functions remotely

$computernames='computer1','computer2','computer3'
    foreach ($computerName in $computerNames){
        Start-Job -name $computerName -InitializationScript $functions -ScriptBlock {param($computer,$something);pingFrom $computer $something} -Args $computerName,'google.com'
    }
    get-job|?{$_.HasMoreData -eq $false -and $_.State -eq 'Completed'}|remove-job
    $jobResults=@()
    do{
        $completedJobs=get-job|?{$_.HasMoreData -eq $true -and $_.State -eq 'Completed'}
        foreach ($job in $completedJobs){
            $minutesElapsed=[math]::round(($job.PSEndTime-$job.PSBeginTime).TotalMinutes,2)
            $computer=$job.Name
            $result=receive-job -id $job.id
            $jobResults+=[pscustomobject]@{
                computerName=$computer
                minutesElapsed=$minutesElapsed
                result=$result
            }
            remove-job -id $job.id
        }
        sleep 1
    }until(!(get-job))
    $jobResults

# Sample output:
#PS C:\Windows\system32>     $jobResults
#computerName  minutesElapsed result
#------------  -------------- ------
#computer1      0.08        {, Pinging google.com [74.125.136.138] with 32 bytes of data:, Reply from 74.125.136.13...
#computer2      0.07        {, Pinging google.com [74.125.136.101] with 32 bytes of data:, Reply from 74.125.136.10...
#computer3      0.07        {, Pinging google.com [74.125.136.100] with 32 bytes of data:, Reply from 74.125.136.10...
# Demo 1: a simple illustration of how to pass functions into jobs

$functions = {
    function foo { write-host "bar" }
    function whoisthere {write-host "big bad wolf"}
    function pingSomething ($uri='amazon.com'){ping $uri}
}

Start-Job -InitializationScript $functions -ScriptBlock {foo}|wait-job|receive-job
Start-Job -InitializationScript $functions -ScriptBlock {whoisthere}|wait-job|receive-job
$job3=Start-Job -InitializationScript $functions -ScriptBlock {param($something);pingSomething $something} -Args 'google.com'
wait-job $job3|Receive-Job
Sample Output:
PS C:\Users\Dee> Start-Job -InitializationScript $functions -ScriptBlock {foo}|wait-job|receive-job
bar
PS C:\Users\Dee> Start-Job -InitializationScript $functions -ScriptBlock {whoisthere}|wait-job|receive-job
big bad wolf
PS C:\Users\Dee> $job3=Start-Job -InitializationScript $functions -ScriptBlock {param($something);pingSomething $something} -Args 'google.com'
PS C:\Users\Dee> wait-job $job3|Receive-Job
Pinging google.com [142.250.72.238] with 32 bytes of data:
Reply from 142.250.72.238: bytes=32 time=13ms TTL=115
Reply from 142.250.72.238: bytes=32 time=28ms TTL=115
Reply from 142.250.72.238: bytes=32 time=14ms TTL=115
Reply from 142.250.72.238: bytes=32 time=14ms TTL=115
Ping statistics for 142.250.72.238:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 13ms, Maximum = 28ms, Average = 17ms

Leave a Reply

Your email address will not be published. Required fields are marked *