-
-
Save Jaykul/6dce64d8d90a93af4bd13dc28bebddd8 to your computer and use it in GitHub Desktop.
Self-cleaning jobs make more jobs to clean themselves up!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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