Skip to content

Instantly share code, notes, and snippets.

@Jaykul
Forked from anonymous/SelfCleaningJobs.ps1
Last active April 8, 2018 01:35
Show Gist options
  • Save Jaykul/6dce64d8d90a93af4bd13dc28bebddd8 to your computer and use it in GitHub Desktop.
Save Jaykul/6dce64d8d90a93af4bd13dc28bebddd8 to your computer and use it in GitHub Desktop.
Self-cleaning jobs make more jobs to clean themselves up!
function New-SelfCleaningJob {
param(
$Name=$([Guid]::NewGuid().Guid)
)
$job = Start-Job -Name $Name { 1..10 | % { Write-Output $_ } }
$jobCleanup = Register-ObjectEvent $job -EventName StateChanged -Action {
if($EventArgs.JobStateInfo.State -eq "Completed") {
# Note this prints to host no matter what's going on right now ....
Receive-Job $Sender | out-host
# Clean up and throw away the job
$Sender | Stop-Job -Passthru | Remove-Job
# And then toss _this_ job too. Yes. Even though it's running us ...
$EventSubscriber.Action | Stop-Job -Passthru | Remove-Job
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment