Automatically Removing a PowerShell Job when it has finished (asynchronously)


I have a PowerShell cmdlet which I use to simplify connecting to another computer with RDP.

Within that cmdlet I run do the following:

As you can see I add the credentials used to connect to the remote machine, then start a job which executes mstsc.exe, waits for it to finish then removes the credentials.

The problem is I have to wait for mstsc to close before deleting the credentials, as otherwise they get removed before mstsc has a chance to establish the connection and I want this cmdlet to be self contained – returning control immediately to the users command prompt so I can run other commands while I am also using the RDP session which means I can’t wait for the job to finish as that mean I am stuck waiting until I disconnect from the remote session:

What I want to do is to be able to Remove-Job once it has completed, perhaps using some kind of callback so I don’t have to manually run another command to clean up the Job once I log out of the RDP session and the Job isn’t left in a Completed state (which is what I am currently doing but obviously this isn’t ‘clean).

For the full cmdlet you can see it here for more context:


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.


Automatically Removing a PowerShell Job when it has finished (asynchronously) by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply