22

I'm looking for a way to automatically do some clean up tasks when the PowerShell session quits. So for example in my profile file I start a process which needs to run in the background for quite a lot of tasks and I would like to automatically close that process when I close the console.

Is there some function the PowerShell automatically calls when closing the session as it does with prompt when displaying the prompt?

poke
  • 369,085
  • 72
  • 557
  • 602

2 Answers2

25

There is the Register-EngineEvent cmdlet which you can use to attach an event handler to the Exiting event:

Register-EngineEvent PowerShell.Exiting -Action { ... }

Note however, that this event will not be fired if you close the console window.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Joey
  • 344,408
  • 85
  • 689
  • 683
  • 2
    Thanks, that works fine but I mostly close my shell without typing `exit` explicitely. Maybe someone else has an idea, otherwise I need to get used to the `exit` ;) – poke Mar 12 '10 at 23:47
  • 3
    Btw. you should add the parameter `-SupportEvent` to prevent PowerShell from printing out the event data whenever the shell starts. -- Or pipe it to `Out-Null`. – poke Mar 12 '10 at 23:51
  • 7
    @poke: I'm using the following little snippet in my profile: `Invoke-Expression "function $([char]4) { exit }"` this allows me to exit PowerShell by pressing Ctrl+D and Enter. Not perfect but short enough to avoid going for the X button. – Joey Mar 13 '10 at 02:23
  • Whoah, that's a nice idea! Thank you very much :) – poke Mar 13 '10 at 16:08
  • I feel `exit` is easier than click x button. – Kellen Stuart Feb 21 '17 at 19:56
0

For an example of how to on exit event. In this case, saving the History of commands on to a file, and maybe stored in a $Profile.

To automatically export the previous commands to a file at the end of a PowerShell session, you can bind the script to the PoSh session termination event (!! The session must be necessarily ended with the exit command, rather than simply closing the PowerShell window):

$HistFile = Join-Path ([Environment]::GetFolderPath('UserProfile')) .ps_history
Register-EngineEvent PowerShell.Exiting -Action { Get-History | Export-Clixml $HistFile } | out-null
if (Test-path $HistFile) { Import-Clixml $HistFile | Add-History }

Quoted from https://woshub.com/powershell-commands-history/

blackgreen
  • 34,072
  • 23
  • 111
  • 129
iPoetDev
  • 41
  • 8