.net - 从 PowerShell 暂停或休眠

标签 .net windows powershell

我对使用 Windows PowerShell 暂停或休眠计算机很感兴趣。你是如何做到这一点的?

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

最佳答案

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

关于.net - 从 PowerShell 暂停或休眠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20713782/

相关文章:

windows - vmrun.exe 的多个问题

powershell - Remove-PSDrive 不会删除驱动器

c# - 为什么 Environment.SpecialFolder.Desktop 是空的

mysql - 任务调度程序可以同时运行多少个任务

c# - 如何确定剪贴板内容的编码

windows - 用于从网络适配器中删除静态配置的 DNS 地址的 Powershell Cmdlet

powershell - 术语 'powershell.exe' 未被识别为 VSTS 任务中的 cmdlet 名称

Powershell/Logparsing 转换数据类型

.net - 在插入语句中使用别名

C# - Moq - 模拟接口(interface)的对象是代理而不是公开的类