PowerShell 窗口防止关机 [英] PowerShell window preventing shutdown

查看:57
本文介绍了PowerShell 窗口防止关机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个 PowerShell 窗口(在 PowerShell 命令提示符下)显示,它会阻止计算机关闭.

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

即如果我打开一个 PowerShell 窗口然后尝试关闭服务器,我会看到结束程序弹出窗口,提示 Windows 无法结束该程序.

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.

如果我从开始菜单、cmd 提示符和指定了 -NoExit 的快捷方式启动 PowerShell,我会得到相同的结果.

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

如何以与 CMD 窗口相同的方式关闭以自动关闭 PowerShell 窗口(如果它在 PowerShell 提示符下)?

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?

或者,PowerShell 是否可以检测到何时启动了关闭并因此自行关闭?

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

推荐答案

此问题已在 Server Fault 上得到解答,所以这是我的解决方案测试代码:

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"

这似乎有效.

这篇关于PowerShell 窗口防止关机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆