Wednesday, January 15, 2020

Background Jobs in PowerShell 7

The PowerShell background jobs feature allows you to run scripts or script blocks in the background. You use the Start-Job command to start a job, and Get-Job ane Receive-Job to view jobs and to get the output of a job.

With PowerShell 7, you have the option of running a job using either PowerShell 7 (ie the default) or using Windows PowerShell 5.1. You indicate it using the -PSVersion parameter and specifying "5.1". Such jobs then run under Windows PowerShell, which can be useful if you are using PowerShell 7 but have scripts that are not yet compatible (eg using WSUS). You can kick off these scripts using background jobs, have that script run in Windows PowerShell, and then incorporate the results in a PowerShell 7 script.

Here's an example:


In this screenshot, you see I am running this in today's build of the day. I then run a simple job and view the job results. By default, PowerShell runs the script in the same version of PowerShell (ie today's daily build). Then I ran that same script but explicitly asked for Window PowerShell 5.1, what the results you can see.

This is a nice feature to assist with backwards compatibility. PowerShell 7 provides great forward compatibility but it's not yet a perfect replacement for Windows PowerShell. Features like this provide a great workaround when a command is not supported natively. 

No comments: