开发者

Powershell profile "on exit" event?

开发者 https://www.devze.com 2022-12-22 23:46 出处:网络
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 l

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 c开发者_运维技巧lose 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?


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.


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)1:

$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 }

Source 1 - from HTTP://woshub.com/. (Not Secure site)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号