Skip to content

Register-EngineEvent Powershell.Exiting does not work. #8000

Open

Description

Steps to reproduce

Register-EngineEvent -SourceIdentifier Powershell.Exiting -Action { Set-Content -Value "Hello there." -Path "$env:TEMP\General Kenobi.txt" }
exit

Instead of exit, the user may also close the Powershell with the x-Button.

Expected behavior

I expect that Powershell executes every command in the -Action parameter before it exits. In this case, I expected that a file General Kenobi.txt would have been written to $env:TEMP.

Actual behavior

Powershell does not execute the action in any case. Not when exiting via exit command and not when exiting by pressing the x-button of the powershell console window.

This not only happens in PS6 but also in PS5.

Environment data

> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      6.1.0
PSEdition                      Core
GitCommitId                    6.1.0
OS                             Microsoft Windows 10.0.17763
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

Activity

  1. vexx32 commented on Oct 11, 2018

    @vexx32
    Collaborator

    This may be related to #6862, perhaps?

  2. added
    WG-Engine
    Issue-Discussion
    on Oct 12, 2018
  3. danielniccoli commented on Dec 11, 2018

    @danielniccoli
    Author

    Any news on this? I am still experiencing this issue with the current preview.

    > $PSVersionTable
    
    Name                           Value
    ----                           -----
    PSVersion                      6.2.0-preview.3
    PSEdition                      Core
    GitCommitId                    6.2.0-preview.3
    OS                             Microsoft Windows 10.0.15063
    Platform                       Win32NT
    PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
    PSRemotingProtocolVersion      2.3
    SerializationVersion           1.1.0.1
    WSManStackVersion              3.0
    
  4. danielniccoli commented on Mar 14, 2019

    @danielniccoli
    Author

    Oddly enough, the following code works. But only if PS is exited via exit command. Closing by pressing the x-button does not trigger the event.

    Register-EngineEvent -SourceIdentifier PowerShell.Exiting -Action {
        "PowerShell exited at {0}" -f (Get-Date) | 
            Out-File -FilePath "$env:TEMP\powershell.log" -Append
    }
  5. danielniccoli commented on Mar 14, 2019

    @danielniccoli
    Author

    Rain Sallow (/u/ta11ow) (@vexx32) #6862 was fixed and merged. I just built from source (master) and the issue still exists.

  6. mklement0 commented on Mar 26, 2019

    @mklement0
    Contributor

    There are several factors at play here:

    • The event never kicks in if PowerShell is not in control of its own termination: Thus, closing the window / quitting the terminal emulator will not run the event handler.

      • This may be a fundamental limitation that is here to stay, but perhaps someone more knowledgeable in this area can tell us.
    • When PowerShell does exit by itself (whether normally or via a script-terminating error generated with throw), the handler does run, but attempts to use of much of PowerShell's regular functionality fail quietly, which is what you saw:

      • When your code is run in-process in a PowerShell session, it does work for me on exit-ing that session.

      • By contrast, if I run it via the CLI (pwsh -c ...) - whether from PowerShell or cmd.exe / Bash - it fails (see test command below). What seems to happen (I'm speculating) is that at the time the script block executes, all modules except Microsoft.PowerShell.Utility have already been unloaded, and attempts to use their commands fail silently and abort execution of the script block instantly.

        • Set-Content is part of module Microsoft.PowerShell.Management, and therefore unavailable; if I substitute Out-File in your command, which comes with Microsoft.PowerShell.Utility, the script block works as expected.
      • In either invocation scenario you also cannot use Write-Output or implicit output to send output to the display (redirection to a file works, though) - only Write-Host is effective.

    At the very least, the documentation needs to be improved to clarify the constraints: I've asked for that in MicrosoftDocs/PowerShell-Docs#4061.

    Here's a test command via the CLI that demonstrates that the handler is invoked, but fails when Set-Content is called:

    # Call from PowerShell itself or Bash.
    pwsh -nop -c '$null = Register-EngineEvent -SourceIdentifier Powershell.Exiting -Action { write-host before; try { Set-Content -ErrorAction stop -Value (Get-Date) -Path ~/t.txt } catch { write-host $_.ToString() }; write-host after }'
    
    # Call from cmd.exe.
    pwsh -nop -c "$null = Register-EngineEvent -SourceIdentifier Powershell.Exiting -Action { write-host before; try { Set-Content -ErrorAction stop -Value (Get-Date) -Path ~/t.txt } catch { write-host $_.ToString() }; write-host after }"

    The above yields:

    before
    The 'Set-Content' command was found in the module 'Microsoft.PowerShell.Management', but the module could not be loaded. For more information, run 'Import-Module Microsoft.PowerShell.Management'.
    after
    
  7. danielniccoli commented on Apr 5, 2019

    @danielniccoli
    Author

    Michael Klement (@mklement0) Michael, thanks for addressing this. Your explanations make sense. I'm not sure what to do with this issue, though.

    On one hand, this is actually by design and I probably should close my ticket.

    On the other hand, the design should be improved in my opinion. The exiting Register-EngineEvent should be fired before anything is unloaded. The PowerShell would greatly benefit from that. The use-case where I actually found out about this event was to disconnect from all open Office 365 sessions when you forgot to explicitly disconnect before closing the Window. So you don't end up being locked out until the stale sessions expire. Which doesn't work when the modules are already unloaded when the event fires.

    Another improvement would be to pass the close-event from the window to the Powershell, so it fires when you close by ALT-F4 or pressing the X. Most PowerShell users are using it on Windows and not on Linux, where you would actually have to run the exit command explicitly. Should I open another issue for that, or is it better to discuss this here? The context is already there.

  8. mklement0 commented on Apr 5, 2019

    @mklement0
    Contributor

    All good points, @Borkason.

    I suggest we get started here by asking for feedback from a subject-matter expert about the original design intent, what could be improved, and what cannot be changed for technical reasons.

    Steve Lee (@SteveL-MSFT), can you help?

  9. added
    Issue-Enhancement
    on Apr 17, 2019
  10. fakcan commented on Apr 19, 2019

    @fakcan

    I'm having the same issue, and looking forward to see any progress on enhancement.

  11. lzybkr commented on Apr 19, 2019

    @lzybkr
    Contributor

    The Win32 Console api supports notifying a console application that it is closing and PowerShell is supposed to receive that notifcation here.

    I know this mechanism works because PSReadLine uses it to avoid a ~6s delay when you click the X to exit. It's possible PSReadLine is getting in the way of PowerShell receiving the notification and hence not firing the event - so I'd test without PSReadLine loaded.

  12. SteveL-MSFT commented on Jul 24, 2019

    @SteveL-MSFT
    Member

    I tried this (explicit exit command) on Windows and macOS and both the exit event triggers the scriptblock and the file is created. Used 6.2.1 and 7-Preview.2.

  13. 23 remaining items

  14. SteveL-MSFT commented on Jul 31, 2023

    @SteveL-MSFT
    Member

    It looks like the process is killed before the handler has a chance to run.

  15. SteveL-MSFT commented on Aug 3, 2023

    @SteveL-MSFT
    Member

    It also appears that .NET has added support for POSIX signals (and translating Windows events), so maybe that can be leveraged https://github.com/dotnet/runtime/blob/904ab9a034c0d8f3ef33579db79c87a6fad70acd/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/PosixSignalRegistration.Windows.cs#L87

  16. bzm3r commented on Aug 4, 2023

    @bzm3r

    It also appears that .NET has added support for POSIX signals (and translating Windows events), so maybe that can be leveraged https://github.com/dotnet/runtime/blob/904ab9a034c0d8f3ef33579db79c87a6fad70acd/src/libraries/System.Private.CoreLib/src/System/Runtime/InteropServices/PosixSignalRegistration.Windows.cs#L87

    Ah, nice! Is the current, Windows-specific behaviour a bug, or a feature?

  17. added
    Resolution-No Activity
    on Jan 31, 2024
  18. ParadoxGBB commented on Jan 31, 2024

    @ParadoxGBB

    I need this as well for cleanup purposes for my project, so I would love if this could please be considered in a future release.

    If the goal is full parity with Windows PowerShell, Core should take it if they can, if not, should remove the feature from Core. As it stands people read the documentation and get confused when it doesn't work.

  19. removed
    Resolution-No Activity
    on Jan 31, 2024
  20. aooohan commented on Mar 13, 2024

    @aooohan

    I need this as well for cleanup purposes for my project, so I would love if this could please be considered in a future release.

    If the goal is full parity with Windows PowerShell, Core should take it if they can, if not, should remove the feature from Core. As it stands people read the documentation and get confused when it doesn't work.

    Agree! I have the same purpose for cleanup, but the documentation is really confusing. 😮‍💨

  21. 5HT2 commented on Aug 9, 2024

    @5HT2

    Any updates on getting this pushed to stable?

  22. added
    WG-NeedsReview
    on Aug 14, 2024
  23. danmacode commented on Apr 17, 2025

    @danmacode

    Han Li (@aooohan) froggie (@5HT2) did you find a way to get this to work?

    I'm forced to do cleanups with either trap [System.Exception] { Cleanup } or try { ... } finally{ Cleanup }.

  24. 5HT2 commented on Apr 26, 2025

    @5HT2

    Daniel M (@danmacode) this appears to work now (Powershell 7.4.6):

    # Helper to register disconnecting exchange when closing
    function Register-DisconnectExchange {
        $null = Register-EngineEvent PowerShell.Exiting –Action {
            Write-ColoredMessage "Disconnecting from Exchange Online..." "Yellow"
            try {
                Disconnect-ExchangeOnline -Confirm:$false
            }
            catch {
                Write-ColoredMessage "Failed to disconnect from Exchange Online." "Red"
            }
        }
    }
  25. danmacode commented on May 2, 2025

    @danmacode

    froggie (@5HT2) sadly, it does not work for me (PowerShell 7.5.1), it only outputs the following:

    Id     Name            PSJobTypeName   State         HasMoreData     Location             Command
    --     ----            -------------   -----         -----------     --------             -------
    4      PowerShell.Exi…                 NotStarted    False                                …
    

    Will try with 7.4.6...

    EDIT: I tried in WSL with 7.5.0 and it works, whether exiting normally or using CTRL+D, the snippet is executed.

  26. santisq commented on Mar 3, 2026

    @santisq

    I have posted this alternative to StackOverflow a while ago which does work correctly using the SetConsoleCtrlHandler WinAPI. Only when closing the window, doesn't work for Process.Kill() of course.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Issue-BugWG-EngineWG-NeedsReview

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions