【问题标题】:PowerShell script can't call itself because "running scripts is disabled on this system" [duplicate]PowerShell脚本无法调用自身,因为“在此系统上禁用了运行脚本”[重复]
【发布时间】:2018-06-08 01:44:57
【问题描述】:

我正在尝试编写一个将 Linux 子系统安装到 PC 上的脚本。代码如下:

function Get-ScriptDirectory { # Gets scripts full path
    Split-Path -parent $PSCommandPath
}

If (-NOT ([Security.Principal.WindowsPrincipal]
  [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(`
  [Security.Principal.WindowsBuiltInRole] "Administrator")) #checks if script is being run as admin
{
    Set-Location -Path $PSScriptRoot
    PowerShell -NoProfile -ExecutionPolicy Unrestricted -Command "&
    {
        Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy
        Unrestricted -File ""Get-ScriptDirectory""' -Verb RunAs}"; # Starts
            #Powershell with admin permissions and executes this script.
    Break
}
Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux #Installs WSL

我不得不使用if 语句来检查脚本是否以系统管理员权限运行(似乎无法再次找到它)。我也在Fedora 主机上的VM 中运行它。我认为它不能调用自己,因为“在这个系统上禁用了运行脚本”这一事实非常奇怪。我取出了if 语句,一切运行正常,它安装了 WSL。

【问题讨论】:

    标签: powershell scripting


    【解决方案1】:

    “正在运行的脚本已禁用...”表明(几乎可以肯定)PowerShell 执行策略设置为“受限”。见Get-Help about_Execution_Policies。

    要启用运行脚本,您需要以管理员身份运行 PowerShell 会话,并在该会话中,Set-ExecutionPolicy 执行策略将 (a) 为您提供足够的安全性以满足您的需求,并且 (b) 允许您执行您觉得舒服的脚本是安全的。见Get-Help Set-ExecutionPolicy。

    【讨论】:

      猜你喜欢
      • 2021-10-27
      • 2017-04-28
      • 2020-03-06
      • 2021-02-22
      • 2021-12-04
      • 2020-06-20
      • 2013-05-03
      • 2019-12-31
      • 2013-10-06
      相关资源
      最近更新 更多