Dot-Net

從 PowerShell 掛起或休眠

  • December 20, 2013

我對使用 Windows PowerShell 暫停或休眠電腦感興趣。你如何做到這一點?

我已經知道Stop-ComputerRestart-Computercmdlet,它們是開箱即用的,但是這些並沒有實現我所追求的功能。

您可以使用類SetSuspendState上的方法System.Windows.Forms.Application來實現這一點。該SetSuspendState方法是靜態方法。

[MSDN] 設置暫停狀態

共有三個參數:

  • 狀態[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

引用自:https://stackoverflow.com/questions/20713782