Get Notification When a Background Job is Done

by Nov 8, 2010

When you assign long-running commands to a background session, you may want to get some notification when the job is completed so you don't have to constantly check its status. Here is how:

$job = Start-Job -Name GetLogFiles { dir $env:windir *.log -recurse -ErrorAction
SilentlyContinue }

Register-ObjectEvent $job StateChanged -Action {
[Console]::Beep(1000,500)
Write-Host ('Job #{0} ({1}) complete.' -f $sender.Id, $sender.Name) -Fore White -Back Red
Write-Host 'Use this command to retrieve the results:'
Write-Host (prompt) -noNewLine
Write-Host ('Receive-Job -ID {0}; Remove-Job -ID {0}' -f $sender.Id)
Write-Host (prompt) -noNewLine
$eventSubscriber | Unregister-Event
$eventSubscriber.Action | Remove-Job
} | Out-Null

This will create a temporary event subscriber that deletes itself once the event is triggered. It will output a message when the background job is completed and also gives a hint on how to retrieve the results from that background job.

Twitter This Tip!
ReTweet this Tip!