PowerShell

PowerShell: Playing with Background Jobs

In this blog post, I’d like to give you a few examples related to PowerShell Background Jobs to build upon. Let’s jump in.

Let’s say I want to ping a few computers. This consumes time. So I want that this task runs in the background as a PowerShell background job.

First, I create some computer names.

$namen = @(
'orf.at'
'sid-500.com'
'8.8.8.8'
'9.9.9.9'
)

Then I will do a quick check whether there are some other jobs running in the background.

Get-Job | Remove-Job 

Then I start my background job “ping” to ping all computer names in $namen. Note that I use the $using variable to be able to use $namen, which is a global variable and therefore out of the scope of the script block.

Start-Job -Name 'ping' `
-ScriptBlock {Test-Connection -ComputerName $using:namen}

A quick look with Get-Job shows that this job is currently running.

Get-Job -State 'Running'

In any case, it is worth mentioning that after the job has finished, the result is not output and that – above all – the result is only output once, unless you use the -Keep parameter.

Receive-Job -Name ping
Receive-Job -Name ping -Keep # do not delete output

That’s it. I hope I was able to shed some light on PowerShell background jobs.

Categories: PowerShell

Tagged as: ,

1 reply »

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.