windows 如何成功更改执行策略并启用 PowerShell 脚本的执行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27753917/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 18:52:43  来源:igfitidea点击:

How do you successfully change execution policy and enable execution of PowerShell scripts

windowspowershell

提问by Andry

I have a problem regarding changing the Execution Policyin my Windows Server 2008+ OS. It is the first time I try to run a script for which I need resource full access and I try the following after starting Powershellin elevated mode:

我在更改Windows Server 2008+ 操作系统中的执行策略时遇到问题。这是我第一次尝试运行需要完全访问资源的脚本,并在以提升模式启动Powershell后尝试以下操作

Set-ExecutionPolicy Unrestricted

But I get this:

但我明白了:

Set-ExecutionPolicy : Windows PowerShell updated your execution policy
successfully, but the setting is overridden by a policy defined at a more
specific scope.  Due to the override, your shell will retain its current
effective execution policy of RemoteSigned. Type "Get-ExecutionPolicy -List"
to view your execution policy settings. For more information please see
"Get-Help Set-ExecutionPolicy".
At line:1 char:1
+ Set-ExecutionPolicy Unrestricted
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : PermissionDenied: (:) [Set-ExecutionPolicy], SecurityException
    + FullyQualifiedErrorId : ExecutionPolicyOverride,Microsoft.PowerShell.Commands.SetExecutionPolicyCommand

Though I am Administrator, I cannot change the Execution Policy. What to do?

虽然我是管理员,但我无法更改执行策略。该怎么办?

采纳答案by Ansgar Wiechers

The error message indicates that the setting you're trying to define via Set-ExecutionPolicyis overridden by a setting in another scope. Use Get-ExecutionPolicy -Listto see which scope has which setting.

该错误消息表明您尝试定义Set-ExecutionPolicy的设置被另一个范围中的设置覆盖。用Get-ExecutionPolicy -List看哪个范围有哪些设置。

PS C:\> Get-ExecutionPolicy -List

        Scope    ExecutionPolicy
        -----    ---------------
MachinePolicy          Undefined
   UserPolicy          Undefined
      Process          Undefined
  CurrentUser          Undefined
 LocalMachine       RemoteSigned

PS C:\> Set-ExecutionPolicy Restricted -Scope Process -Force
PS C:\> Set-ExecutionPolicy Unrestricted -Scope CurrentUser -Force
Set-ExecutionPolicy : Windows PowerShell updated your execution policy
successfully, but the setting is overridden by a policy defined at a more
specific scope.  Due to the override, your shell will retain its current
effective execution policy of Restricted. Type "Get-ExecutionPolicy -List"
to view your execution policy settings. ...
PS C:\> Get-ExecutionPolicy -List

        Scope    ExecutionPolicy
        -----    ---------------
MachinePolicy          Undefined
   UserPolicy          Undefined
      Process         Restricted
  CurrentUser       Unrestricted
 LocalMachine       RemoteSigned

PS C:\> .\test.ps1
.\test.ps1 : File C:\test.ps1 cannot be loaded because running scripts is
disabled on this system. ...
PS C:\> Set-ExecutionPolicy Unestricted -Scope Process -Force
PS C:\> Set-ExecutionPolicy Restricted -Scope CurrentUser -Force
Set-ExecutionPolicy : Windows PowerShell updated your execution policy
successfully, but the setting is overridden by a policy defined at a more
specific scope.  Due to the override, your shell will retain its current
effective execution policy of Restricted. Type "Get-ExecutionPolicy -List"
to view your execution policy settings. ...
PS C:\> Get-ExecutionPolicy -List

        Scope    ExecutionPolicy
        -----    ---------------
MachinePolicy          Undefined
   UserPolicy          Undefined
      Process       Unrestricted
  CurrentUser         Restricted
 LocalMachine       RemoteSigned

PS C:\> .\test.ps1
Hello World!

As you can see, both settings were defined despite the error, but the setting in the more specific scope (Process) still takes precedence, either preventing or allowing script execution.

如您所见,尽管存在错误,但仍定义了两个设置,但更具体的范围 ( Process) 中的设置仍具有优先权,无论是阻止还是允许脚本执行。

Since the default scope is LocalMachinethe error could be caused by a setting in the CurrentUseror Processscope. However, a more common reason is that script execution was configured via a group policy (either local or domain).

由于默认范围是LocalMachine错误可能是由CurrentUserProcess范围中的设置引起的。但是,更常见的原因是脚本执行是通过组策略(本地或域)配置的。

A local group policy can be modified by a local administrator via gpedit.msc(Local Group Policy Editor) as described in this answer.

本地管理员可以通过gpedit.msc(本地组策略编辑器)修改本地组策略,如本答案所述

A domain group policy cannot be superseded by local settings/policies and must be changed by a domain admin via gpmc.msc(Group Policy Management) on a domain controller.

域组策略不能被本地设置/策略取代,必须由域管理员通过gpmc.msc域控制器上的(组策略管理)进行更改。

For both local and domain policies the setting can be defined as a computer setting:

对于本地和域策略,设置可以定义为计算机设置:

Computer Configuration
`-Administrative Templates
  `-Windows Components
    `-Windows PowerShell -> Turn on Script Execution

or as a user setting:

或作为用户设置:

User Configuration
`-Administrative Templates
  `-Windows Components
    `-Windows PowerShell -> Turn on Script Execution

The former are applied to computer objects, whereas the latter are applied to user objects. For local polices there is no significant difference between user and computer policies, because user policies are automatically applied to all users on the computer.

前者适用于计算机对象,而后者适用于用户对象。对于本地策略,用户策略和计算机策略之间没有显着差异,因为用户策略会自动应用于计算机上的所有用户。

A policy can have one of three states (or five states if you count the 3 settings available for the state Enabledseparately):

策略可以具有以下三种状态之一(如果单独计算可用于状态Enabled的 3 个设置,则为五种状态):

  • Not Configured: policy does not control PowerShell script execution.
  • Enabled: allow PowerShell script execution.
    • Allow only signed scripts: allow execution of signed scripts only (same as Set-ExecutionPolicy AllSigned).
    • Allow local scripts and remote signed scripts: allow execution of all local scripts (signed or not) and of signed scripts from remote locations (same as Set-ExecutionPolicy RemoteSigned).
    • Allow all scripts: allow execution of local and remote scripts regardless of whether they're signed or not (same as Set-ExecutionPolicy Unrestricted).
  • Disabled: disallow PowerShell script execution (same as Set-ExecutionPolicy Restricted).
  • 未配置:策略不控制 PowerShell 脚本的执行。
  • 已启用:允许 PowerShell 脚本执行。
    • 仅允许签名脚本允许执行签名脚本(与 相同Set-ExecutionPolicy AllSigned)。
    • 允许本地脚本和远程签名脚本:允许从远程位置执行所有本地脚本(已签名或未签名)和已签名脚本(与 相同Set-ExecutionPolicy RemoteSigned)。
    • 允许所有脚本:允许执行本地和远程脚本,无论它们是否已签名(与 相同Set-ExecutionPolicy Unrestricted)。
  • 已禁用:禁止 PowerShell 脚本执行(与 相同Set-ExecutionPolicy Restricted)。

Changes made via Set-ExecutionPolicyonly become effective when local and domain policies are set to Not Configured(execution policy Undefinedin the scopes MachinePolicyand UserPolicy).

Set-ExecutionPolicy仅当本地和域策略设置为“未配置”Undefined范围MachinePolicy和中的执行策略UserPolicy)时,通过 via 所做的更改才会生效。

回答by Andry

The problem is that Windows does not allow all scripts to be executed in Unrestrictedmode. Actually, no matter the execution policy for your user (even if administrator), the Local Group Policywill take priority.

问题是 Windows 不允许在Unrestricted模式下执行所有脚本。实际上,无论您的用户(即使是管理员)的执行策略如何,Local Group Policy都将优先。

And by default the local group script execution policy is such for which scripts are not allowed to be executed. We need to change it!

默认情况下,本地组脚本执行策略是不允许执行脚本的。我们需要改变它!

Changing the Local Group Execution Policy

更改本地组执行策略

We do this via the Local Group Policy Editorwhich you can reach by searching in the Windows Search bar for "group policy". Or do this:

我们通过Local Group Policy Editor您可以通过在 Windows 搜索栏中搜索“组策略”来达到此目的。或者这样做:

  1. Open the Management Console by hitting Win + rand typing command mmc.
  2. Go to File -> Add Remove Snap In....
  3. In the left pane find Group Policy Object Editorand add it.
  4. Close the form.
  1. 通过点击Win + r并输入命令来打开管理控制台mmc
  2. File -> Add Remove Snap In...
  3. 在左窗格中找到Group Policy Object Editor并添加它。
  4. 关闭表格。

Then on the left pane the group editor can be expanded. Expand it and navigate to Computer Configuration -> Administrative Templates -> Windows Components.

然后在左窗格中可以展开组编辑器。展开它并导航到Computer Configuration -> Administrative Templates -> Windows Components.

enter image description here

在此处输入图片说明

Then to Windows PowerShell.

然后到Windows PowerShell.

enter image description here

在此处输入图片说明

So select Turn on Script Execution. Change configuration to Enabledand specify Allow all scriptsin Execution Policy.

所以选择Turn on Script Execution. 将配置更改为EnabledAllow all scripts在 中指定Execution Policy

enter image description here

在此处输入图片说明

Confirm by hitting Okand close the Management Console.

通过点击Ok并关闭管理控制台来确认。

回答by Jhayes2118

If you are running into this with visual studio 2015 recently, check if there are any updates for nuget package manager in tools > extensions and updates>

如果您最近使用 Visual Studio 2015 遇到此问题,请检查工具 > 扩展和更新 > 中的 nuget 包管理器是否有任何更新

回答by Perry Tribolet

If the PowerShell ExecutionPolicy is being set by a Domain Controller through a group policy, you'll have to reset the ExecutionPolicy to "Bypass" in the registry after every boot. I've created a pair of startup scripts to automate the process. Below, I describe my process.

如果 PowerShell ExecutionPolicy 是由域控制器通过组策略设置的,则您必须在每次启动后在注册表中将 ExecutionPolicy 重置为“绕过”。我创建了一对启动脚本来自动化这个过程。下面,我描述一下我的过程。

Create a folder called %USERPROFILE%\Documents\StartupScripts and then place a PowerShell script called ExecutionPolicy.ps1 in it with following code:

创建一个名为 %USERPROFILE%\Documents\StartupScripts 的文件夹,然后使用以下代码在其中放置一个名为 ExecutionPolicy.ps1 的 PowerShell 脚本:

Push-Location
Set-Location HKLM:\Software\Policies\Microsoft\Windows\PowerShell
Set-ItemProperty . ExecutionPolicy "Bypass"
Pop-Location

Then create a file called %USERPROFILE%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\Startup.cmd and place the following code in it:

然后创建一个名为 %USERPROFILE%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\Startup.cmd 的文件,并将以下代码放入其中:

PowerShell -Version 3.0 -Command "Set-ExecutionPolicy Unrestricted" >> "%TEMP%\StartupLog.txt" 2>&1
PowerShell -Version 3.0 "%USERPROFILE%\Documents\StartupScripts\ExecutionPolicy.ps1" >> "%TEMP%\StartupLog.txt" 2>&1

This script will run at the start of every login.

此脚本将在每次登录开始时运行。

回答by Rashmi Jain

Even if @Ansgar Wiechers's Answer doesn't work.. Then there can be issue with you MachinePolicy Scope. So there can be one workaround for that issue is.. Edit the Registry Value for the ExecutionPolicy Key at

即使@Ansgar Wiechers 的回答不起作用.. 那么您的 MachinePolicy 范围可能会出现问题。因此,该问题的一种解决方法是.. 编辑 ExecutionPolicy 键的注册表值在

HKEY_LOCAL_MACHINE -> SOFTWARE -> Policies -> Microsoft -> Windows -> Powershell

HKEY_LOCAL_MACHINE -> 软件 -> 策略 -> Microsoft -> Windows -> Powershell

it worked for me to execute ps script after trying out so many solutions.

在尝试了这么多解决方案后,它对我来说执行 ps 脚本很有用。

回答by Marc

Add the following to a file named psa.cmdand put in a folder included your PATH :

将以下内容添加到名为的文件中psa.cmd,并将其放入包含您的 PATH 的文件夹中:

POWERSHELL -Command "$enccmd=[Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes((Get-Content '%1' | Out-String)));POWERSHELL -EncodedCommand $enccmd"

Now you can run any powershell script as in:

现在您可以运行任何 powershell 脚本,如下所示:

psa script.ps1