代码之家  ›  专栏  ›  技术社区  ›  DevelopingChris

为什么我的PowerShell脚本没有运行?

  •  91
  • DevelopingChris  · 技术社区  · 18 年前

    我编写了一个简单的批处理文件作为PowerShell脚本,当它们运行时我会收到错误。

    它在我路径的脚本目录中。

    Cannot be loaded because the execution of scripts is disabled on this system. 
    please see "get-help about-signing".
    

    我找过帮助,但没什么帮助。

    7 回复  |  直到 7 年前
        1
  •  95
  •   Peter Mortensen Pieter Jan Bonestroo    7 年前

    它可能是PowerShell的默认安全级别,该级别(IIRC)只运行签名脚本。

    尝试键入:

    set-executionpolicy remotesigned
    

    这将告诉PowerShell允许本地(即在本地驱动器上)运行未签名脚本。

    然后再次尝试执行脚本。

        2
  •  70
  •   Peter Mortensen Pieter Jan Bonestroo    7 年前

    你需要跑步 Set-ExecutionPolicy :

    Set-ExecutionPolicy Restricted <-- Will not allow any powershell scripts to run.  Only individual commands may be run.
    
    Set-ExecutionPolicy AllSigned <-- Will allow signed powershell scripts to run.
    
    Set-ExecutionPolicy RemoteSigned <-- Allows unsigned local script and signed remote powershell scripts to run.
    
    Set-ExecutionPolicy Unrestricted <-- Will allow unsigned powershell scripts to run.  Warns before running downloaded scripts.
    
    Set-ExecutionPolicy Bypass <-- Nothing is blocked and there are no warnings or prompts.
    
        3
  •  14
  •   Peter Mortensen Pieter Jan Bonestroo    7 年前

    用途:

    Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process
    

    始终使用上面的命令启用在当前会话中执行PowerShell。

        4
  •  12
  •   Peter Mortensen Pieter Jan Bonestroo    7 年前

    我可以通过如下方式调用PowerShell来绕过此错误:

    powershell -executionpolicy bypass -File .\MYSCRIPT.ps1
    

    也就是说,我添加了 -executionpolicy bypass 我调用脚本的方式。

    这适用于Windows7 Service Pack 1。我刚接触过PowerShell,因此可能会有一些我不知道的注意事项。

    [编辑2017-06-26]我继续在其他系统上使用此技术,包括Windows 10和Windows 2012 R2,没有问题。

    这是我现在用的。这可以防止我通过单击脚本意外地运行它。当我在调度器中运行它时,我添加了一个参数:“scheduler”,这将绕过提示。

    这也会在窗口末尾暂停,以便我可以看到PowerShell的输出。

    if NOT "%1" == "scheduler" (
       @echo looks like you started the script by clicking on it.
       @echo press space to continue or control C to exit.
       pause
    )
    
    C:
    cd \Scripts
    
    powershell -executionpolicy bypass -File .\rundps.ps1
    
    set psexitcode=%errorlevel%
    
    if NOT "%1" == "scheduler" (
       @echo Powershell finished.  Press space to exit.
       pause
    )
    
    exit /b %psexitcode%
    
        5
  •  5
  •   hackjutsu Jan Galinski    9 年前
    Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process
    

    即使发生以下错误,上述命令也对我有效:

    Access to the registry key 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell' is denied.
    
        6
  •  5
  •   danday74    9 年前

    另外,你可能需要包括 .\ 在脚本名称前面。例如:

    .\scriptname.ps1
    
        7
  •  1
  •   Brian Mains    13 年前

    命令 set-executionpolicy unrestricted 将允许您创建的任何脚本作为登录用户运行。只需确保使用 set-executionpolicy signed 注销前的命令。

    推荐文章