How to handle close event of PowerShell window if user clicks on Close('X') button

后端 未结 3 764
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-06 11:25

I want to run some code before PowerShell 2.0 window is closed. For this I tried:

PS > register-engineevent PowerShell.Exiting -action {get-process | out-file c:

相关标签:
3条回答
  • 2020-12-06 11:54

    The unhandled exception occurs because garbage collection has already disposed your handler by the time the unmanaged method is called. You can get around that by storing it in a static field:

    private static HandlerRoutine s_rou;
    
    public static void SetHandler()
    {
        if (s_rou == null)
        {
            s_rou = new HandlerRoutine(ConsoleCtrlCheck);
            SetConsoleCtrlHandler(s_rou, true);
        }
    }
    
    0 讨论(0)
  • 2020-12-06 12:00

    When you click the X to close you are closing the application hosting PowerShell. This application would need to handle the exit situation. I believe the default PS host is the Windows console which is obviously not doing what you need. You could host PowerShell in a custom host and handle the exit events. I'm on a Mac right now but maybe running under the PS ISE would handle this for you?

    0 讨论(0)
  • 2020-12-06 12:19

    Unfortunately, you can't do this. The only time an exiting event will get called is if you type "exit" at the PowerShell prompt.

    This is how I hook up my exiting event:

     $null = Register-EngineEvent -SourceIdentifier `
         ([System.Management.Automation.PsEngineEvent]::Exiting) -Action { # Put code to run here }
    
    0 讨论(0)
提交回复
热议问题