Automatically Removing a PowerShell Job when it has finished (asynchronously)
I know this is a very old question... You can use Register-ObjectEvent
to clean up after jobs. Jobs have a StateChanged
event that has an EventSubscriber
parameter passed to it containing details of the event and the source job.
Here's an example. Once the job completes the callback will remove both itself and the source job.
$job = Start-Job { Start-Sleep -Seconds 2 }Register-ObjectEvent -InputObject $job -EventName StateChanged -Action { Unregister-Event $EventSubscriber.SourceIdentifier Remove-Job $EventSubscriber.SourceIdentifier Remove-Job -Id $EventSubscriber.SourceObject.Id} | Out-Null
So register a scheduledjob to run in 5 minutes that will remove the completed job. I am pretty sure that you can do something like:
Register-ScheduledJob -ScriptBlock {param($computername); Wait-Job -Name $ComputerName|remove-job} -Trigger @{Frequency="Once";At=(get-date).AddMinutes(5).ToString("h:MM tt")} -argumentlist $computername
Then just give your connection a name when you do your Start-Job by appending -Name $ComputerName
to the end of the command. That way 5 minutes after you launch it a scheduled task kicks off that finds and clears out that job by name.