2013-12-20 209 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