且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PowerShell 脚本不会作为 Windows 计划任务执行

更新时间:2022-12-02 18:46:48

如果您遇到的问题是执行策略,那么您还可以设置特定 PowerShell 调用的执行策略.这是我在通过计划任务执行 PowerShell 时通常会做的事情:

If the problem you're having is with Execution Policy, then you can also set the execution policy of a specific invocation of PowerShell. This is what I usually do when executing PowerShell through a scheduled task:

powershell.exe -NoProfile -NoLogo -NonInteractive -ExecutionPolicy Bypass -File \\path\to\script.ps1

为什么?

-NoProfile

这可确保您不依赖用户的 PowerShell 配置文件中的任何内容,并避免执行额外代码的开销.

Why?

-NoProfile

This ensures that you don't rely on anything in the user's PowerShell profile, and avoids the overhead of executing that additional code.

这几乎没有关系;如果您正在捕获脚本的输出,也许可以.主要是让我感觉好多了.

This mostly doesn't matter; maybe it does if you're capturing the output of your script. Mostly it makes me feel better.

确保您的任务不会在脚本中的某些内容意外提示用户时无限期地等待.使用此开关,脚本将直接退出;至少你会有一个错误代码而不是一个挂起的脚本.

Ensures that your task won't wait indefinitely if something in your script unexpectedly prompts the user. With this switch, the script will just exit instead; at least you'll have an error code instead of a hanging script.

您可以在此处使用 Unrestricted 或您喜欢的任何执行策略.这可能是您最需要的.

You can use Unrestricted here or whichever execution policy you like. This is probably the one you need the most.

因为我不希望任务依赖于一个全局的非默认设置,您将来可能有其他原因要更改.如果某个其他进程依赖于不同的执行策略,那么它不会以这种方式与您的任务不一致.

Because I don't want the task to depend on a global non-default setting that you may have other reasons to change in the future. If some other process depends on a different execution policy, then it's not at odds with your task this way.

另外,不必更改默认值总是很好.较少记住/记录/测试.

Plus it's always nice not to have to change the defaults. Less to remember/document/test.

有关 0x1 导致计划任务的一些其他原因,请参阅 JohnLBevan 的回答.

See JohnLBevan's answer for some additional causes of 0x1 result in a scheduled task.