首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在运行powershell进程时阻止windows 10机器休眠/休眠?

如何在运行powershell进程时阻止windows 10机器休眠/休眠?
EN

Stack Overflow用户
提问于 2020-12-05 12:11:44
回答 3查看 4.7K关注 0票数 3

我有一个powershell进程,它从远程服务器读取记录并将它们复制到本地数据库中。当它运行时,它可能运行8-12小时。

如何防止计算机在此期间关闭(或进入睡眠/休眠模式)?我知道我可以调整“电源和睡眠设置”,将电脑设置为永不休眠,但这不是我想要的--我确实希望它在进程不运行时进入睡眠状态。

我知道如果netflix或youtube视频正在运行,睡眠/hibernate将被暂停,我希望计算机在powershell进程运行时也能这样做。

powershell进程在桌面上的一个命令窗口中运行--我很高兴屏幕保护程序被激活,但我不想发生的是在8小时后唤醒机器,然后发现进程在计算机进入睡眠前只运行了10分钟!

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2020-12-05 20:04:14

通过一些额外的努力,您可以使用标准 实现所需的行为,方法是使用自定义的、始终处于状态的电源方案,该是根据需要创建的,并在脚本运行期间暂时激活:

注意:

  • 在下面查找评论# YOUR CODE GOES HERE .

有关基于this answer.的.NET / Windows的替代,请参阅

代码语言:javascript
运行
复制
# Define the properties of a custom power scheme, to be created on demand.
$schemeGuid = 'e03c2dc5-fac9-4f5d-9948-0a2fb9009d67' # randomly created with New-Guid
$schemeName = 'Always on'
$schemeDescr = 'Custom power scheme to keep the system awake indefinitely.'

# Helper function that ensures that the most recent powercfg.exe call succeeded.
function assert-ok { if ($LASTEXITCODE -ne 0) { throw } }

# Determine the currently active power scheme, so it can be restored at the end.
$prevGuid = (powercfg -getactivescheme) -replace '^.+([-0-9a-f]{36}).+$', '$1'
assert-ok

# Temporarily activate a custom always-on power scheme; create it on demand.
try {

  # Try to change to the custom scheme.
  powercfg -setactive $schemeGuid 2>$null
  if ($LASTEXITCODE -ne 0) { # Changing failed -> create the scheme on demand.
    # Clone the 'High performance' scheme.
    $null = powercfg -duplicatescheme SCHEME_MIN $schemeGuid
    assert-ok
    # Change its name and description.
    $null = powercfg -changename $schemeGuid $schemeName $schemeDescr
    # Activate it
    $null = powercfg -setactive $schemeGuid
    assert-ok
    # Change all settings to be always on.
    # Note: 
    #   * Remove 'monitor-timeout-ac', 'monitor-timeout-dc' if it's OK
    #     for the *display* to go to sleep.
    #   * If you make changes here, you'll have to run powercfg -delete $schemeGuid 
    #     or delete the 'Always on' scheme via the GUI for changes to take effect.
    #   * On an AC-only machine (desktop, server) the *-ac settings aren't needed.
    $settings = 'monitor-timeout-ac', 'monitor-timeout-dc', 'disk-timeout-ac', 'disk-timeout-dc', 'standby-timeout-ac', 'standby-timeout-dc', 'hibernate-timeout-ac', 'hibernate-timeout-dc'
    foreach ($setting in $settings) {
      powercfg -change $setting 0 # 0 == Never
      assert-ok
    }
  }
  
  # YOUR CODE GOES HERE.
  # In this sample, wait for the user to press Enter before exiting.
  # Before that, the 'Always on' power scheme should remain in
  # effect, and the machine shouldn't go to sleep.
  pause

} finally { # Executes even when the script is aborted with Ctrl-C.
  # Reactivate the previously active power scheme.
  powercfg -setactive $prevGuid
}

您可以从上面创建一个包装器脚本,将要执行的脚本的路径传递给该脚本。

如果您不介意修改当前活动的方案,可以使用Kerr's answer中所示的方法,使用每个设置的powercfg -change <setting> <value-in-minutes>调用(/x / -x/change /-change的别名),在每个调用中使用以下d30名称;传递0作为<value-in-minutes>表示的<value-in-minutes>。

  • monitor-timeout-ac
  • monitor-timeout-dc
  • disk-timeout-ac
  • disk-timeout-dc
  • standby-timeout-ac
  • standby-timeout-dc
  • hibernate-timeout-ac
  • hibernate-timeout-dc

但是请注意,这样的更改是持久化的,因此可能希望稍后恢复原始值,这需要额外的努力。

票数 4
EN

Stack Overflow用户

发布于 2020-12-05 21:13:06

提供基于.NET / Windows的替代以替代powercfg.exe-based solution

注意:

  • 解决方案使用Add-Type按需编译C#代码,这将在当前会话中首次调用代码时造成性能损失。

  • 在同一会话中调用::StayAwake($false)是非常重要的,以便清除所发出的电源请求。

  • 在下面查找评论# YOUR CODE GOES HERE .

这个解决方案是由MarkusEgle.从this C# answer中改编的。

代码语言:javascript
运行
复制
Add-Type -ErrorAction Stop -Name PowerUtil -Namespace Windows -MemberDefinition @'

    // Member variables.
    static IntPtr _powerRequest;
    static bool _mustResetDisplayRequestToo;

    // P/Invoke function declarations.
    [DllImport("kernel32.dll")]
    static extern IntPtr PowerCreateRequest(ref POWER_REQUEST_CONTEXT Context);

    [DllImport("kernel32.dll")]
    static extern bool PowerSetRequest(IntPtr PowerRequestHandle, PowerRequestType RequestType);

    [DllImport("kernel32.dll")]
    static extern bool PowerClearRequest(IntPtr PowerRequestHandle, PowerRequestType RequestType);

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)]
    static extern int CloseHandle(IntPtr hObject);

    // Availablity Request Enumerations and Constants
    enum PowerRequestType
    {
        PowerRequestDisplayRequired = 0,
        PowerRequestSystemRequired,
        PowerRequestAwayModeRequired,
        PowerRequestMaximum
    }

    const int POWER_REQUEST_CONTEXT_VERSION = 0;
    const int POWER_REQUEST_CONTEXT_SIMPLE_STRING = 0x1;

    // Availablity Request Structures
    // Note:  Windows defines the POWER_REQUEST_CONTEXT structure with an
    // internal union of SimpleReasonString and Detailed information.
    // To avoid runtime interop issues, this version of 
    // POWER_REQUEST_CONTEXT only supports SimpleReasonString.  
    // To use the detailed information,
    // define the PowerCreateRequest function with the first 
    // parameter of type POWER_REQUEST_CONTEXT_DETAILED.
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    struct POWER_REQUEST_CONTEXT
    {
        public UInt32 Version;
        public UInt32 Flags;
        [MarshalAs(UnmanagedType.LPWStr)]
        public string SimpleReasonString;
    }

    /// <summary>
    /// Prevents the system from going to sleep, by default including the display.
    /// </summary>
    /// <param name="enable">
    ///   True to turn on, False to turn off. Passing True must be paired with a later call passing False.
    ///   If you pass True repeatedly, subsequent invocations take no actions and ignore the parameters.
    ///   If you pass False, the remaining paramters are ignored.
    //    If you pass False without having passed True earlier, no action is performed.
    //// </param>
    /// <param name="includeDisplay">True to also keep the display awake; defaults to True.</param>
    /// <param name="reasonString">
    ///   A string describing why the system is being kept awake; defaults to the current process' command line.
    ///   This will show in the output from `powercfg -requests` (requires elevation).
    /// </param>
    public static void StayAwake(bool enable, bool includeDisplay = true, string reasonString = null)
    {
      
      if (enable)
      {

        // Already enabled: quietly do nothing.
        if (_powerRequest != IntPtr.Zero) { return; }

        // Configure the reason string.
        POWER_REQUEST_CONTEXT powerRequestContext;
        powerRequestContext.Version = POWER_REQUEST_CONTEXT_VERSION;
        powerRequestContext.Flags = POWER_REQUEST_CONTEXT_SIMPLE_STRING;
        powerRequestContext.SimpleReasonString = reasonString ?? System.Environment.CommandLine; // The reason for making the power request.

        // Create the request (returns a handle).
        _powerRequest = PowerCreateRequest(ref powerRequestContext);

        // Set the request(s).
        PowerSetRequest(_powerRequest, PowerRequestType.PowerRequestSystemRequired);
        if (includeDisplay) { PowerSetRequest(_powerRequest, PowerRequestType.PowerRequestDisplayRequired); }
        _mustResetDisplayRequestToo = includeDisplay;

      }
      else
      {

        // Not previously enabled: quietly do nothing.
        if (_powerRequest == IntPtr.Zero) { return; }

        // Clear the request
        PowerClearRequest(_powerRequest, PowerRequestType.PowerRequestSystemRequired);
        if (_mustResetDisplayRequestToo) { PowerClearRequest(_powerRequest, PowerRequestType.PowerRequestDisplayRequired); }
        CloseHandle(_powerRequest);
        _powerRequest = IntPtr.Zero;

      }
  }

  // Overload that allows passing a reason string while defaulting to keeping the display awake too.
  public static void StayAwake(bool enable, string reasonString)
  {
    StayAwake(enable, false, reasonString);
  }

'@

try {

  # Create power request(s) that keep the system awake.
  # Pass $false as the 2nd argument to allow the display to go to sleep.
  # The reason string is visible when you run `powercfg.exe -requests` to show current requests
  # (requires elevation).
  # Defaults: keep the display awake too, use the current process' command line as the reason string.
  [Windows.PowerUtil]::StayAwake($true, $true, "Running long-running script $PSCommandPath.")

  # YOUR CODE GOES HERE.
  # In this sample, wait for the user to press Enter before exiting.
  # Before that, the system should stay awake indefinitely.
  pause

} finally { # This ensures that the previous scheme is restored even when the script is aborted with Ctrl-C.

  # Clear the power requests.
  [Windows.PowerUtil]::StayAwake($false)

}
票数 1
EN

Stack Overflow用户

发布于 2021-07-01 07:17:23

我使用的简单的一层衬垫:

代码语言:javascript
运行
复制
Powercfg /x -standby-timeout-ac 0
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65156768

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档