我正在尝试运行从cmd.exe调用PowerShell脚本的cmd文件,但遇到以下错误:

无法加载Management_Install.ps1,因为在此系统上禁用了脚本的执行。

我运行了以下命令:

Set-ExecutionPolicy -ExecutionPolicy Unrestricted

当我从PowerShell运行Get-ExecutionPolicy时,它返回Unrestricted。

Get-ExecutionPolicy

输出:

Unrestricted

cd“C:\Projects\Microsoft.Practices.ESB\Source\Samples\Management Portal\Install\Scripts”powershell。\管理安装.ps1 1警告:正在运行x86 PowerShell。。。无法加载文件C:\Projects\Microsoft.Practices.ESB\Source\Samples\Management Portal\Install\Scripts\Management_Install.ps1,因为在此系统上禁用了脚本的执行。有关详细信息,请参阅“get-helpabout_signing”。第1行字符:25.\Management_Install.ps1<<<1类别信息:未指定:(:)[],PSSecurityExceptionFullyQualifiedErrorId:运行时异常C: \Projects\Microsoft.Practices.ESB\Source\Samples\Management Portal\Install\Scripts>PAUSE按任意键继续。


系统为Windows Server 2008 R2。

我做错了什么?


当前回答

我们可以通过以下命令获取当前ExecutionPolicy的状态:

Get-ExecutionPolicy

默认情况下,它是受限的。为了允许执行PowerShell脚本,我们需要将此ExecutionPolicy设置为Unrestricted或Bypass。

我们可以使用以下任何PowerShell命令将当前用户的策略设置为绕过:

Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Unrestricted -Force

Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Bypass -Force

无限制策略加载所有配置文件并运行所有脚本。如果您运行的是从Internet下载的未签名脚本,则会在运行前提示您获得许可。

而在Bypass策略中,在脚本执行过程中不会阻止任何内容,也不会出现任何警告或提示。BypassExecutionPolicy比Unrestricted更宽松。

其他回答

Win+R并键入复制粘贴命令,然后按OK:

powershell Set-ExecutionPolicy -Scope "CurrentUser" -ExecutionPolicy "RemoteSigned"

然后执行脚本。

然后恢复更改,如:

powershell Set-ExecutionPolicy -Scope "CurrentUser" -ExecutionPolicy "AllSigned"

我遇到了类似的问题,并注意到Windows Server 2012上的默认cmd运行的是x64版本。

对于Windows 11、Windows 10、Windows 7、Windows 8、Windows Server 2008 R2或Windows Server 2012,请以管理员身份运行以下命令:

x86(32位)打开C:\Windows\SysWOW64\cmd.exe运行命令powershell Set ExecutionPolicy RemoteSigned

x64(64位)打开C:\Windows\system32\cmd.exe运行命令powershell Set ExecutionPolicy RemoteSigned

您可以使用检查模式

在CMD中:echo%PROCESSOR_ARCHITECURE%在Powershell中:[Environment]::Is64BitProcess

参考文献:MSDN-Windows PowerShell执行策略Windows-32位vs 64位目录说明

我今天也有同样的问题。64位执行策略不受限制,而32位执行策略受到限制。

以下是如何远程更改32位策略:

Invoke-Command -ComputerName $servername -ConfigurationName Microsoft.PowerShell32 -scriptblock {Set-ExecutionPolicy unrestricted}

转到注册表路径HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Shell\1\ShellIds\Microsoft.PowerShell,并将ExecutionPolicy设置为RemoteSigned。

我发现这一行最适合我的一台Windows Server 2008 R2服务器。其他一些人在我的PowerShell脚本中没有这行代码时没有问题:

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Force -Scope Process