从 PowerShell 挂起或休眠



我对使用Windows PowerShell挂起或休眠计算机感兴趣。您如何实现这一目标?

我已经知道现成包含的

Stop-ComputerRestart-Computer cmdlet,但它们无法实现我所追求的功能。

您可以在System.Windows.Forms.Application类上使用 SetSuspendState 方法来实现此目的。SetSuspendState方法是一种静态方法。

[MSDN] 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,我仍然能够使用键盘和鼠标唤醒计算机。

希望这些对您有用。

关机%windir%System32shutdown.exe -s

重新启动%windir%System32shutdown.exe -r

注销%windir%System32shutdown.exe -l

待机%windir%System32rundll32.exe powrprof.dll,SetSuspendState Standby

休眠%windir%System32rundll32.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

我在 C:\Windows\System32 中使用关闭可执行文件

shutdown.exe /h

我试图将其减少到一行,但遇到了错误。这是我的解决方案:

[Void][System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") 
[System.Windows.Forms.Application]::SetSuspendState("Hibernate", $false, $false);

最新更新