从PowerShell挂起或休眠 [英] Suspend or hibernate from PowerShell
问题描述
我对使用Windows PowerShell挂起或休眠计算机感兴趣.您如何实现的?
I am interested in using Windows PowerShell to suspend or hibernate a computer. How do you achieve this?
我已经知道了 Stop-Computer
和 Restart-Computer
cmdlet,它们是现成的,但它们并不能实现我所需要的功能之后.
I am already aware of the Stop-Computer
and Restart-Computer
cmdlets, which are included out of the box, but these do not achieve the functionality that I am after.
推荐答案
您可以在 System.Windows.Forms.Application
类上使用 SetSuspendState
方法来实现此目的. SetSuspendState
方法是静态方法.
You can use the SetSuspendState
method on the System.Windows.Forms.Application
class to achieve this. The SetSuspendState
method is a static method.
有三个参数:
- 状态
[System.Windows.Forms.PowerState]
- 强制
[bool]
- disableWakeEvent
[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);
将其放入更完整的功能中可能看起来像这样:
Putting this into a more complete function might look something like this:
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
.
Note: In my testing, the -DisableWake
option did not make any distinguishable difference that I am aware of. I was still capable of using the keyboard and mouse to wake the computer, even when this parameter was set to $true
.
这篇关于从PowerShell挂起或休眠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!