Is it possible to create a PowerShell job using start-job which will terminate itself once completed?
For example the script block would check some conditions and write the result to a log file, after which it should terminate itself (the job within which it is running).
In other words I would start many short jobs from the main script block, but I don’t need to receive anything from them and I would like to avoid keeping track of them and having to use remove-job to terminate them all.
Sort of. You can’t do that from inside the job itself (because it’s usually running in a different process), but you can register an event that fires when the job finishes and cleans up after itself. Here’s some demo code of that:
$job = Start-Job -ScriptBlock { Start-Sleep -Seconds 10 }
$null = Register-ObjectEvent $job -EventName StateChanged -Action {
if ($eventArgs.JobStateInfo.State -eq [System.Management.Automation.JobState]::Completed)
{
Write-Host -ForegroundColor Green 'Event triggering'
# This command removes the original job
$sender | Remove-Job -Force
# These commands remove the event registration
$eventSubscriber | Unregister-Event -Force
$eventSubscriber.Action | Remove-Job -Force
}
}
Write-Verbose -Verbose 'Before:'
Get-Job | Out-Host
Thank for the quick reply! One question:
what is the $sender variable?
$sender, $eventArgs and $eventSubscriber are all automatic variables set inside the Action block of an event subscription. There are a few others as well, in the about_Automatic_Variables help file.