【发布时间】:2013-12-20 23:55:49
【问题描述】:
我对使用 Windows PowerShell 挂起或休眠计算机感兴趣。你是如何做到这一点的?
我已经知道 Stop-Computer 和 Restart-Computer cmdlet,它们是开箱即用的,但它们无法实现我所追求的功能。
【问题讨论】:
标签: .net windows powershell
我对使用 Windows PowerShell 挂起或休眠计算机感兴趣。你是如何做到这一点的?
我已经知道 Stop-Computer 和 Restart-Computer cmdlet,它们是开箱即用的,但它们无法实现我所追求的功能。
【问题讨论】:
标签: .net windows powershell
您可以使用System.Windows.Forms.Application 类上的SetSuspendState 方法来实现此目的。 SetSuspendState 方法是静态方法。
共有三个参数:
[System.Windows.Forms.PowerState]
[bool]
[bool]
调用SetSuspendState方法:
# 1. Define the power state you wish to set, from the
# System.Windows.Forms.PowerState enumeration.
$PowerState = [System.Windows.Forms.PowerState]::Suspend;
# 2. Choose whether or not to force the power state
$Force = $false;
# 3. Choose whether or not to disable wake capabilities
$DisableWake = $false;
# Set the power state
[System.Windows.Forms.Application]::SetSuspendState($PowerState, $Force, $DisableWake);
把它放到一个更完整的函数中可能看起来像这样:
function Set-PowerState {
[CmdletBinding()]
param (
[System.Windows.Forms.PowerState] $PowerState = [System.Windows.Forms.PowerState]::Suspend
, [switch] $DisableWake
, [switch] $Force
)
begin {
Write-Verbose -Message 'Executing Begin block';
if (!$DisableWake) { $DisableWake = $false; };
if (!$Force) { $Force = $false; };
Write-Verbose -Message ('Force is: {0}' -f $Force);
Write-Verbose -Message ('DisableWake is: {0}' -f $DisableWake);
}
process {
Write-Verbose -Message 'Executing Process block';
try {
$Result = [System.Windows.Forms.Application]::SetSuspendState($PowerState, $Force, $DisableWake);
}
catch {
Write-Error -Exception $_;
}
}
end {
Write-Verbose -Message 'Executing End block';
}
}
# Call the function
Set-PowerState -PowerState Hibernate -DisableWake -Force;
注意:在我的测试中,-DisableWake 选项没有产生我所知道的任何明显差异。即使此参数设置为$true,我仍然能够使用键盘和鼠标唤醒计算机。
【讨论】:
disableWakeEvent...这个参数可以防止SetWaitableTimer()唤醒电脑。 SetWaitableTimer() 由任务计划程序使用(至少)。在此处查看详细信息:msdn.microsoft.com/en-us/library/windows/desktop/aa373235.aspx
Add-Type -AssemblyName System.Windows.Forms 以便它可以找到请求的类。
希望你觉得这些有用。
关机%windir%\System32\shutdown.exe -s
重启%windir%\System32\shutdown.exe -r
注销%windir%\System32\shutdown.exe -l
待机%windir%\System32\rundll32.exe powrprof.dll,SetSuspendState Standby
休眠%windir%\System32\rundll32.exe powrprof.dll,SetSuspendState Hibernate
编辑:
正如@mica 在评论中指出的那样,挂起(睡眠)实际上是在休眠。显然这发生在 Windows 8 及更高版本中。要“睡觉”,请禁用休眠或获取外部 Microsoft 工具(非内置)
“Microsoft 的 Sysinternals 工具之一是 PsShutdown,使用命令 psshutdown -d -t 0 它会正确睡眠,而不是休眠计算机”
来源:https://superuser.com/questions/42124/how-can-i-put-the-computer-to-sleep-from-command-prompt-run-menu
【讨论】:
Invoke-AU3Shutdown 32 用于待机。所以这是另一种选择。
shutdown.exe /h 是更简单的休眠方式。
$Env:WinDir 是 powershell 方式。
我使用 C:\Windows\System32 中的关闭可执行文件
shutdown.exe /h
【讨论】:
我尝试将其简化为单行,但出现错误。这是我的解决方案:
[Void][System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[System.Windows.Forms.Application]::SetSuspendState("Hibernate", $false, $false);
【讨论】: