Running Powershell script as a background job

Sometimes we would like not to wait for a script block to complete and start another script block parallelly. We have the possibility to do that.

Just use the invoke-command cmdlet and create a new job in a new session.

For new session creation use the new-pssession cmdlet after enabling the psremoting.

As your script block will run in a new session we have to take care about the variables which we would like to use inside the script block. So these variables should be provided as arguments to the new script block. This argument list is just a normal array anyway.

If you want to get back some result from this script block just use a simple variable to collect the information.

Enable-PSRemoting -Force | Out-Null
$s = new-pssession -computername '.' -Name 'Write and Sleep'
$Param1 = "Hello World!"
$Param2 = "Hello Universe!"
$Arguments = @($Param1, $Param2)
 $Job = Invoke-Command -Session $s -AsJob -ArgumentList $Arguments -ScriptBlock
 {
 Param (
 [string]$World,
 [string]$Universe
 )

 Write-Host -ForegroundColor "Yellow" $World
 Write-Host -ForegroundColor "Yellow" $Universe
 Write-Host -ForeGroundColor "Green" "Let's sleep a bit!"
Start-Sleep -s 6000
  Write-Host -ForeGroundColor "Green" "Once more"
 Write-Host -ForegroundColor "Yellow" $World
 Write-Host -ForegroundColor "Yellow" $Universe

 $ScriptBlockOutput = $Error
 }
#And from here we can continue the main script without waiting for the other block to finish.
Write-Host "Hello Script Block"
Do-SomethingIntresting -now

To get the value for the $ScriptBlockOutput use the next line

  $JobOutput = invoke-command -session $s -scriptblock {$ScriptBlockOutput}
# The $Job.state parameter can be used for checking whether if the $Job completed or Failed.
  $Job.state -eq 'Completed'
  $Job.state -eq 'Failed'

Then we need to close the session

 Get-PSSession | where {$_.Name -eq 'Write and Sleep'} | Remove-PSSession
 Disable-PSRemoting -force  | Out-Null

Conclusion
Nothing special – but why wait for something? Just the basics for the posts later 🙂 Follow me 😛

Advertisements

2 thoughts on “Running Powershell script as a background job”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s