通过一些额外的努力,您可以通过以下方式实现所需的行为标准powercfg.exe utility https://learn.microsoft.com/en-us/windows-hardware/design/device-experiences/powercfg-command-line-options,通过使用定制、始终开启的电源方案它是按需创建的,并在脚本运行期间临时激活:
Note:
-
寻找评论# YOUR CODE GOES HERE
below.
-
For a 基于 .NET / Windows API 的替代方案, see 这个答案 https://stackoverflow.com/a/65162017/45375.
# 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
}
你可以创建一个wrapper上面的脚本,您可以将要执行的脚本的路径传递给该脚本。
如果您不介意修改目前活跃 scheme,您可以使用中所示的方法克尔的回答 https://stackoverflow.com/users/3996028/kerr,使用每个设置powercfg -change <setting> <value-in-minutes>
calls (/x
/ -x
是一个别名/change
/ -change
),使用以下之一<setting>
每次通话中的姓名;通过0
as <value-in-minutes>
代表never:
monitor-timeout-ac
monitor-timeout-dc
disk-timeout-ac
disk-timeout-dc
standby-timeout-ac
standby-timeout-dc
hibernate-timeout-ac
hibernate-timeout-dc
但请注意,这些变化是执着的, so 你可能想要restore稍后的原始值,这需要额外的努力。