admin管理员组

文章数量:1531270

默认windows 10 powershell 的安全策略是可以执行单步命令,但不能运行脚本。尝试运行脚本时会出现如下错误:

File cannot be loaded because running scripts is disabled on this system. 

解决办法

查询执行策略

Get-ExecutionPolicy -List

默认情况下的输出为:

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

设置执行策略

根据需要选择安全策略,一般为 CurrentUser 设置 RemoteSigned 策略。
这样就可以执行本地生成的脚本文件。

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

取消执行策略

Set-ExecutionPolicy -ExecutionPolicy Undefined -Scope CurrentUser

详细的执行策略及其范围

PowerShell 执行策略:

  • AllSigned
    所有的脚本都需要签名才能运行
  • Bypass
    所有都能运行,没有警告或提醒。
  • Default
    默认的策略:
    • Windows客户端采用 Restricted.
    • Windows服务端采用 RemoteSigned.
  • RemoteSigned
    下载的需要签名才能运行,本地生成的不需要
  • Restricted
    不能运行脚本,只能执行单步命令
  • Undefined
    未定义,如果所有scope都是未定义,则采用 Default 的策略
  • Unrestricted
    可以执行,但是运行下载的脚本会产生警告。

执行策略范围:

  • MachinePolicy
    对于本计算机的所有用户设置一个组策略
  • UserPolicy
    对于当前用户设置一个组策略
  • Process
    只影响当前的 PoweShell 会话。
  • CurrentUser
    只影响当前用户
  • LocalMachine
    只影响这台计算机的所有用户

参考:

  • about_Execution_Policies
  • How to Enable PowerShell Scripts in Windows 10 via PowerShell Execution Policy

本文标签: 脚本功能Windowspowershell