2013-12-20 198 views
6

我对使用Windows PowerShell挂起或休眠计算机感兴趣。你如何做到这一点?从PowerShell挂起或休眠

我已经知道Stop-ComputerRestart-Computer cmdlet,这些cmdlet是开箱即用的,但它们不能实现我之后的功能。

回答

16

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

[MSDN] SetSuspendState

有三个参数:

  • 国家[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); 

把这个变成一个更完整的功能,可能是这个样子:

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,我仍然可以使用键盘和鼠标唤醒计算机。

+0

关于'disableWakeEvent' ...此参数可以防止'SetWaitableTimer()'来唤醒计算机。 Task Scheduler使用的SetWaitableTimer()(至少)。在这里看到详细信息:http://msdn.microsoft.com/en-us/library/windows/desktop/aa373235.aspx – CoolCmd

+4

这在我的控制台上不起作用,我不得不添加'Add-Type -AssemblyName System .Windows.Forms“,所以它可以找到请求的类。 – Eris

12

希望你找到这些有用的。

关机%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工具 (没有内置)“一个微软的Sysinternals工具的使用命令psshutdown -d -t 0它将正确睡PsShutdown,不冬眠,一台计算机” 来源:https://superuser.com/questions/42124/how-can-i-put-the-computer-to-sleep-from-command-prompt-run-menu

+0

那个待命命令对我来说是冬眠的。 – Mica

+0

@Mica答案是3岁。 :P刚刚更新了答案 –

+0

由于我已经安装了AutoIt,因此我最终使用了它们的shutdown cmdlet,其中'Invoke-AU3Shutdown 32'用于备用。所以这是另一种选择。 – Mica

3

我用在C关机可执行文件:\ Windows \ System32下

shutdown.exe /h