Windows PowerShell Job Tips and Tricks
The Windows PowerShell jobs engine allows us to run local and/or remote tasks in the background of an elevated console session. For instance, let's say we needed to find all .PDF files in a huge folder tree:
Get-ChildItem -Path E:\ -Recurse -Filter *.pdf
If your E:\ drive is anything like mine, the previous task is going to hang up your PowerShell console session for a long time. Annoying!
By contrast, if we put the previous Get-ChildItem call into a job, we can happily continue working in our session:
Start-Job -Name 'PDFSearch-EDrive' -ScriptBlock { Get-ChildItem -Path E:\ -Recurse -Filter *.pdf } Id Name PSJobTypeName State HasMoreData Location -- ---- ------------- ----- ----------- -------- 2 PDFSearch-ED... BackgroundJob Running True localhost
We can use Get-Job to check job status:
Get-Job -Id 2 Id Name PSJobTypeName State HasMoreData Location -- ---- ------------- ----- ----------- -------- 2 PDFSearch-CD... BackgroundJob Completed True localhost
Finally, we can use Retrieve-Job with the -Keep switch to view the job results and keep them in memory for future reference:
Receive-Job -Id 2 -Keep | Select-Object -First 2 Directory: E:\lab\db\commbutton Mode LastWriteTime Length Name ---- ------------- ------ ---- -a---- 4/23/2015 9:55 AM 27667CCENTv3.pdf -a---- 4/23/2015 9:55 AM 56913ITTv3.pdf
All of this information I've given you is well and good, but it should just be review. I want to take your PowerShell job skills to the next level by teaching you four "power user" tips and tricks:
- Saving your job results by default
- Leveraging the -AsJob switch parameter
- Troubleshooting child jobs
- Making use of community contributions
With no further ado, let's begin!
Saving Your Job Results by Default
If you forget to add the -Keep switch parameter to the Receive-Job cmdlet, your job results go up the proverbial chimney. Personally, that default behavior in Windows PowerShell ticks me off.
My friend and Windows PowerShell MVP Jeff Hicks taught me a neat trick to ensure that Receive-Job always runs with the -Keep switch, at least for the current session.
All we have to do is modify the default parameter values for our session. Try this:
$PSDefaultParameterValues = @{'Receive-Job:Keep'=$true}
Now create, run, and receive another PowerShell job. You should find that the job results persist in your current runspace thanks to our new default parameter value. We can view the contents of this automatic variable at any time:
$PSDefaultParameterValues Name Value ---- ----- Receive-Job:Keep True
This default parameter change disappears when you close your current PowerShell session. Thus, you'll want to add that line to your PowerShell profile(s) as necessary if it's something you need for the future.
For some reason I'm inspired to remind you that you're free to export job results to, say, a text file or a delimited file. For instance, the following code creates a job that pulls event log data, and then stores it in a simple text file:
Start-Job -Name 'systemlog' -ScriptBlock { Get-EventLog -LogName System -Newest 50 } Receive-Job -Id 2 -Keep | Out-File -Path '.\event.txt'
Ever the detective, PowerShell MVP Boe Prox taught me another way to retrieve job data if we forget the -Keep switch. For this example, I'll create a job showing processes that consume more than 100MB of RAM on my Windows 8.1 system:
Start-Job -Name 'highmem' -ScriptBlock { Get-Process | Where-Object { $_.WS -gt 100MB } }
If I run a Receive-Job and then a Get-Job again, the HasMoreData property is False as expected:
Receive-Job -Name highmem Get-Job -Name highmem Id Name PSJobTypeName State HasMoreData Location -- ---- ------------- ----- ----------- -------- 4 highmem BackgroundJob Completed False localhost
Okay, here's where the .NET magic comes in. I'll store the highmem job as a variable, and then check out its ChildJobs.output property:
PS C:\> $highmem.ChildJobs.output | Select-Object -First 2 Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 1156 37 190532 167728 794 8,549.25 1120 chrome 188 26 168340 157188 915 434.78 1672 chrome
Whoa—isn't that awesome?
Leveraging the -AsJob Switch Parameter
Instead of formally defining background jobs with Get-Job, we can tack on the -AsJob parameter to some cmdlets to create ad hoc background jobs. Let's see which of the PowerShell core cmdlets support this switch:
PS C:\> Get-Command -ParameterName AsJob | Select-Object -Property Name Name ---- Get-WmiObject Invoke-Command Invoke-WmiMethod Remove-WmiObject Restart-Computer Set-WmiInstance Stop-Computer Test-Connection
Let's focus on Invoke-Command because it uses WS-Man remoting and is therefore more efficient than the old DCOM/RPC remoting used by most of those other commands.
Check this out:
Invoke-Command -ComputerName dc1,mem1,mem2 -ScriptBlock { Get-EventLog -LogName Security -Newest 2 } -AsJob Id Name PSJobTypeName State HasMoreData Location -- ---- ------------- ----- ----------- -------- 15 Job15 RemoteJob Running True dc1,mem1,mem2
Notice that the PSJobTypeName is RemoteJob instead of the BackgroundJob type we've seen thus far.
Troubleshooting Child Jobs
Something many PowerShell administrative scripts don't (yet) understand is that jobs in PowerShell always consist of one parent job and one or more child jobs. For instance, consider the Invoke-Command -AsJob example we used previously:
Invoke-Command -ComputerName dc1,mem1,mem2 -ScriptBlock { Get-EventLog -LogName Security -Newest 2 } -AsJob Id Name PSJobTypeName State HasMoreData Location -- ---- ------------- ----- ----------- -------- 15 Job15 RemoteJob Running True dc1,mem1,mem2
That ID of 15 refers to the parent job container, and I'm sure that PowerShell has a separate child job defined for each computer queried by our Get-EventLog script block. How do I know? By using the -IncludeChildJob switch of the Get-Job cmdlet:
PS C:\> Get-Job -IncludeChildJob Id Name PSJobTypeName State HasMoreData Location -- ---- ------------- ----- ----------- -------- 15 Job15 RemoteJob Completed True dc1,mem1,mem2 16 Job16 Completed True dc1 17 Job17 Completed True mem1 18 Job18 Completed True mem2
Understanding child jobs makes troubleshooting easier because a failure in a child job can cause the parent job to report a failed status. To that point, we can retrieve child job contents simply by using the child job ID:
Receive-Job -Id 18 -Keep Index Time EntryType Source InstanceID Message PSCompute rName ----- ---- --------- ------ ---------- ------- --------- 4104 Jan 13 10:09 SuccessA... Microsoft-Windows... 4624 An acco... mem2 4103 Jan 13 10:09 SuccessA... Microsoft-Windows... 4672 Special... mem2
Making Use of Community Contributions
Please keep in mind that Windows PowerShell is largely a community-driven technology stack; for proof, notice how many PowerShell features are hosted by Microsoft in GitHub repositories.
Once again, Boe Prox offers us an alternative to the native PowerShell job engine in his PoshRSJob module. Let's use PowerShellGet to install it:
Find-Module -Name poshrsjob | Install-Module -Verbose
Boe wrote the PoshRSJob module in an attempt to improve background job performance in PowerShell. He also wanted to give users the ability to throttle their jobs' resource utilization. Here's the command set:
PS C:\> Get-Command -Module PoshRSJob | Select-Object -Property Name Name ---- Get-RSJob Receive-RSJob Remove-RSJob Start-RSJob Stop-RSJob Wait-RSJob
Let's say we want to write a job that checks the status of the Windows Update service on our three servers, but we want to make the job more resource-friendly on our system and the network. For instance, normally Invoke-Command operates on 25 computers simultaneously, but here we want to throttle that value back to two. Enter Start-RSJob!
Start-RSJob -Name 'wucheck' -Throttle 2 -ScriptBlock { Invoke-Command -ComputerName dc1, mem1, mem2 -ScriptBlock {Get-Service -Name wuauserv}}
Do you see the -Throttle switch? You should also notice peppier performance with the RSJob architecture as compared to the PowerShell core job engine.
One more thing—these RSJobs are managed separately from PowerShell core jobs. Therefore, don't forget to use Get-RSJob and Receive-RSJob in your experimentation.