Monday, March 12, 2018

Cleaning up if a PowerShell process gets terminated unexpectedly

One user wanted to have a Finally block in a PowerShell script run even if the script's execution was terminated by the End command of Task Scheduler. This isn't directly possible; no user-mode code will execute in a process once it's terminated. What is possible, however, is to start another script that waits for the original to exit (it'd need to be supplied the watched process's PID) and then performs any cleanup. If the cleanup should only happen in case of abnormal termination of the main script, the watchdog script's process can be terminated at the conclusion of the main script's work.

No comments:

Post a Comment