错误消息表明您尝试通过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!
如您所见,尽管存在错误,但仍定义了两个设置,但更具体的范围 (Process) 中的设置仍然优先,阻止或允许脚本执行。
由于默认范围是LocalMachine,因此错误可能是由CurrentUser 或Process 范围中的设置引起的。但是,更常见的原因是脚本执行是通过组策略(本地或域)配置的。
本地管理员可以通过gpedit.msc(本地组策略编辑器)修改本地组策略,如this answer 中所述。
域组策略不能被本地设置/策略取代,必须由域管理员通过域控制器上的gpmc.msc(组策略管理)进行更改。
对于本地和域策略,该设置可以定义为计算机设置:
Computer Configuration
`-Administrative Templates
`-Windows Components
`-Windows PowerShell -> Turn on Script Execution
或作为用户设置:
User Configuration
`-Administrative Templates
`-Windows Components
`-Windows PowerShell -> Turn on Script Execution
前者应用于计算机对象,而后者应用于用户对象。对于本地策略,用户策略和计算机策略之间没有显着差异,因为用户策略会自动应用于计算机上的所有用户。
一个策略可以具有三种状态之一(如果您分别计算状态 Enabled 可用的 3 个设置,则可以具有五个状态):
-
未配置:策略不控制 PowerShell 脚本执行。
-
启用:允许执行 PowerShell 脚本。
-
只允许签名脚本:只允许执行签名脚本(同
Set-ExecutionPolicy AllSigned)。
-
允许本地脚本和远程签名脚本:允许执行所有本地脚本(签名或未签名)和远程位置的签名脚本(与
Set-ExecutionPolicy RemoteSigned 相同)。
-
允许所有脚本:允许执行本地和远程脚本,无论它们是否已签名(与
Set-ExecutionPolicy Unrestricted 相同)。
-
已禁用:禁止执行 PowerShell 脚本(与
Set-ExecutionPolicy Restricted 相同)。
通过Set-ExecutionPolicy 所做的更改仅在本地和域策略设置为未配置时生效(执行策略Undefined 在MachinePolicy 和UserPolicy 范围内)。