If you must run some code before PowerShell should exit, you could simply use a try…finally clause like this:
try { # some code Start-Sleep -Seconds 20 } finally { # this gets executed even if the code in the try block throws an exception [Console]::Beep(4000,1000) }
This one simulates a long-running script. Even if you close the PowerShell window: the code inside the finally block will be executed before PowerShell ends.
Of course this requires that the script is actually running.