I want to run some code before PowerShell window is closed. For this I tried:
PS > register-engineevent PowerShell.Exiting -action {get-process | out-file c:\work\powershellexiteventcalled.txt}
It works fine if user closes PowerShell window using exit command (i.e. exit <ENTER>). But it does not work if user closes it by clicking on Close ('X') button on top right.
I could not find any way to handle this. I also tried to do it the following way, but this does not work either:
PS > $query = "Select * from __InstanceDeletionEvent WITHIN 5 WHERE TargetInstance ISA 'Win32_Process' AND TargetInstance.Name='powershell.exe'"
PS > Register-WmiEvent -Query $query -Action {get-process | out-file c:\work\powershellexiteventcalled.txt}
Please guide how I can achieve this task.