Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

If I have a PowerShell window (at the PS command prompt) on display it prevents the computer shutting down.

i.e. if I open a powershell window and then try to shutdown the server, I get the End Program popup saying Windows cannot end this program

I get the same result if I start the powershell from the start menu, from a cmd prompt and from a shortcut with -NoExit specified.

Any ideas how I can get shutdown to automatically close a powershell window (if it is at the PS prompt) in the same way as it would for a CMD window?

Alternatively, is it possible for PowerShell to detect when a shutdown has been initiated and therefore close itself?

Update:

Going down the alternative route as suggested by pk. I have come up with this test code:

Write-Host "PowerShellBlockingShutdown.ps1 Started"

$global:shuttingDown = $false
$sysevent = [microsoft.win32.systemevents]
Register-ObjectEvent -InputObject $sysevent -EventName "SessionEnding" -Action {$global:shuttingDown = $true; Write-Host "  SessionEnding"} 
Register-ObjectEvent -InputObject $sysevent -EventName "SessionEnded"  -Action {$global:shuttingDown = $true; Write-Host "  SessionEnded"} 

do {
    Start-Sleep -Seconds 3
    if ($global:shuttingDown) {break}
    Write-Host "  Waiting for Shutdown"
} while ($true)

Write-Host "PowerShellBlockingShutdown.ps1 Finished"

Which seems to work

share|improve this question

1 Answer 1

up vote 1 down vote accepted

I'm blatantly cut/pasting this answer from another site (since linking is frowned upon and I don't have a better answer). I do believe this will resolve your problem.

...it looks like you can set up a Event watcher using Register-ObjectEvent using [microsoft.win32.systemevents] and watching for either SessionEnding or SessionEnded. I haven't had time to test this out, but you could look at using something like this:

$sysevent = [microsoft.win32.systemevents]
Register-ObjectEvent -InputObject $sysevent -EventName "SessionEnding" -Action {"Shutdown/Logoff detected.";Get-Process -Name Powershell | Stop-Process -Force}

More information about this class can be found here: http://msdn.microsoft.com/en-us/library/microsoft.win32.systemevents_events.aspx

share|improve this answer
    
Cheers. I saw that and was wondering what it all meant :-) I'll have a play and get back to you –  FrinkTheBrave Apr 17 '12 at 6:53
1  
I've added my solution to the question –  FrinkTheBrave Apr 17 '12 at 7:51

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.