3

If I have a PowerShell window (at the PowerShell 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 PowerShell from the start menu, from a cmd prompt and from a shortcut with -NoExit specified.

How can I get shutdown to automatically close a PowerShell window (if it is at the PowerShell 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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
FrinkTheBrave
  • 3,894
  • 10
  • 46
  • 55

1 Answers1

2

This question was answered on Server Fault, so here is my solution 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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
FrinkTheBrave
  • 3,894
  • 10
  • 46
  • 55