Skip to content

Instantly share code, notes, and snippets.

@jkdba
Last active June 12, 2022 23:57
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save jkdba/8d1562b4ff45ac237c4eba2cc0f153a5 to your computer and use it in GitHub Desktop.
PowerShell Automatically Cleanup Job on Completion Using a Registered Object StateChanged Event
#Build Job Name to be unique
$JobName = "ExampleJob"
$JobNameCount = (get-job | Where-Object Name -like $JobName*).Count
$JobName = "$($JobName)_$($JobNameCount)"
#Define and Start job
$Job = Start-Job -Name $JobName -ScriptBlock { Start-Sleep 60 }
#Create Event to clean up job after complete
Register-ObjectEvent -InputObject $Job -EventName "StateChanged" -Action {
#Logic to handle state change
if($sender.State -match "Complete"){
Remove-Job $sender.Id
}
else{
Write-Warning -Message "Job $($sender.Name) completed with an unexpected status: $($sender.State)."
}
#Unregister event and remove event job
Unregister-Event -SubscriptionId $Event.EventIdentifier
Remove-Job -Name $event.SourceIdentifier
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment