首页 > 解决方案 > 执行 powershell 命令后批处理文件暂停

问题描述

我要做的是为实际进程(cmd.exe)设置-ExecutionPolicy(允许脚本)

如果在 cmd.exe 中写入此命令(以管理员身份):

PowerShell.exe -ExecutionPolicy Unrestricted

输出是:

Windows PowerShell 
Copyright (C) Microsoft Corporation. Alle Rechte vorbehalten.

Lernen Sie das neue plattformübergreifende PowerShell kennen – https://aka.ms/pscore6

比我输入这个命令:

PowerShell.exe -Command "SomePowerShellScript.ps"

一切正常。

如果我从批处理文件中尝试相同的操作,它会在第一个命令之后暂停。

Microsoft 描述了我使用第一个命令而不是特定于 Set-ExecutionPolicy 的 Powershell 的原因:

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-5.1

PowerShell.exe -ExecutionPolicy Unrestricted

--> 设置ExecutionPolicy为cmd和powershell(脚本可以启动)

PowerShell.exe -Command Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope Process

--> 仅在实际 powershell.exe 进程上设置策略(不允许启动脚本)

为了澄清,如果可能的话,我不想将 LocalMachine/CurrentUser 的执行策略设置为 Unrestricted。

为了解释这个问题,批处理文件仅供“懒惰”的人直接启动 Powershell 脚本,而无需设置 ExecutionPolicy(因此它通过双击工作)。

有谁知道为什么批处理文件在第一个命令之后暂停(我也尝试过调用 powershell.exe)?

感谢您的回复:)。

标签: powershellbatch-file

解决方案


明显的暂停是PowerShell.exe -ExecutionPolicy Unrestricted实际进入交互式PowerShell 会话的结果,您必须手动exit执行该会话(除此之外,仅为该会话(进程)设置执行策略)。

如果您将-ExecutionPolicy Unrestricted(or -ExecutionPolicy Bypass)放在-File参数之前,则在尝试执行传递给的脚本文件之前设置执行策略 - 仅适用于进程-File,并且执行应该成功(除非组策略抢先覆盖持久配置的执行策略命令行:

powershell.exe -ExecutionPolicy Unrestricted -File SomePowerShellScript.ps1

您也可以使用-Command,但请注意这会改变参数的解释;值得注意的是,您必须使用.\SomePowerShellScript.ps1来引用要执行的脚本。

有关更多信息,请参阅此答案


推荐阅读