You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Register-EngineEvent Powershell.Exiting does not work. #8000
Issue-BugIssue has been identified as a bug in the productWG-Enginecore PowerShell engine, interpreter, and runtimeWG-NeedsReviewNeeds a review by the labeled Working Group
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
Reacted by Olivier F., Sean, Dipricyn, Doug Maurer, Joel Christophel, Soberia, Mike Estes, Jan Šmucr, ymping, garidozv and 1 more
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:
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
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.
Reacted by Michael Klement, Fırat, isxaker and Andy Bolton
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.
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.
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.
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.
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. 😮💨
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.
Issue-BugIssue has been identified as a bug in the productWG-Enginecore PowerShell engine, interpreter, and runtimeWG-NeedsReviewNeeds a review by the labeled Working Group
Activity
vexx32 commentedon Oct 11, 2018
This may be related to #6862, perhaps?
danielniccoli commentedon Dec 11, 2018
Any news on this? I am still experiencing this issue with the current preview.
danielniccoli commentedon Mar 14, 2019
Oddly enough, the following code works. But only if PS is exited via
exitcommand. Closing by pressing the x-button does not trigger the event.danielniccoli commentedon Mar 14, 2019
Rain Sallow (/u/ta11ow) (@vexx32) #6862 was fixed and merged. I just built from source (master) and the issue still exists.
mklement0 commentedon Mar 26, 2019
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.
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 orcmd.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 exceptMicrosoft.PowerShell.Utilityhave already been unloaded, and attempts to use their commands fail silently and abort execution of the script block instantly.Set-Contentis part of moduleMicrosoft.PowerShell.Management, and therefore unavailable; if I substituteOut-Filein your command, which comes withMicrosoft.PowerShell.Utility, the script block works as expected.In either invocation scenario you also cannot use
Write-Outputor implicit output to send output to the display (redirection to a file works, though) - onlyWrite-Hostis 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-Contentis called:The above yields:
danielniccoli commentedon Apr 5, 2019
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
exitcommand explicitly. Should I open another issue for that, or is it better to discuss this here? The context is already there.mklement0 commentedon Apr 5, 2019
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?
fakcan commentedon Apr 19, 2019
I'm having the same issue, and looking forward to see any progress on enhancement.
lzybkr commentedon Apr 19, 2019
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
PSReadLineuses it to avoid a ~6s delay when you click the X to exit. It's possiblePSReadLineis getting in the way of PowerShell receiving the notification and hence not firing the event - so I'd test without PSReadLine loaded.SteveL-MSFT commentedon Jul 24, 2019
I tried this (explicit
exitcommand) 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.23 remaining items
SteveL-MSFT commentedon Jul 31, 2023
It looks like the process is killed before the handler has a chance to run.
SteveL-MSFT commentedon Aug 3, 2023
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
bzm3r commentedon Aug 4, 2023
Ah, nice! Is the current, Windows-specific behaviour a bug, or a feature?
ParadoxGBB commentedon Jan 31, 2024
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.
aooohan commentedon Mar 13, 2024
Agree! I have the same purpose for cleanup, but the documentation is really confusing. 😮💨
fix(powershell): due to a bug in PowerShell, we have to cleanup first…
fix(powershell): due to a bug in PowerShell, we have to cleanup first…
5HT2 commentedon Aug 9, 2024
Any updates on getting this pushed to stable?
danmacode commentedon Apr 17, 2025
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 }ortry { ... } finally{ Cleanup }.5HT2 commentedon Apr 26, 2025
Daniel M (@danmacode) this appears to work now (Powershell 7.4.6):
danmacode commentedon May 2, 2025
froggie (@5HT2) sadly, it does not work for me (PowerShell
7.5.1), it only outputs the following:Will try with
7.4.6...EDIT: I tried in WSL with
7.5.0and it works, whether exiting normally or usingCTRL+D, the snippet is executed.santisq commentedon Mar 3, 2026
I have posted this alternative to StackOverflow a while ago which does work correctly using the
SetConsoleCtrlHandlerWinAPI. Only when closing the window, doesn't work forProcess.Kill()of course.