Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell script “on exit” event?

Tags:

powershell

Instead of calling a function at the end of all scripts to perform cleanup tasks, I'm looking to register for an 'on return' event for when the script (not the PowerShell session) is finished.

  • A script can return at various points though (eg, no records to process), so the current situation is problematic.
  • Register-EngineEvent applies to the PowerShell session, and operators run scripts manually, thus it's problematic.

I can't find a list of built-in powershell events or an alternative solution.

like image 904
svandragt Avatar asked Dec 30 '25 23:12

svandragt


1 Answers

@Vesper wrote it as a comment, but a try/finally block is definitely what I would suggest for this:

try {
    # some code
} finally {
    # this gets executed even if the code in the try block throws an exception
}
like image 83
briantist Avatar answered Jan 04 '26 04:01

briantist



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!