我正在try 从ASP.NET Core Web API运行PowerShell脚本.请查看以下环境详细信息:

.NET SDKs installed:
  3.1.403 [C:\Program Files\dotnet\sdk]
  7.0.200 [C:\Program Files\dotnet\sdk]
  7.0.201 [C:\Program Files\dotnet\sdk]
  7.0.306 [C:\Program Files\dotnet\sdk]
  7.0.400 [C:\Program Files\dotnet\sdk]
  8.0.100-preview.3.23178.7 [C:\Program Files\dotnet\sdk]
  8.0.101 [C:\Program Files\dotnet\sdk]

该API在.NET 7上运行;以下是.csproj文件:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net7.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.PowerShell.SDK" Version="7.3.9" />
  </ItemGroup>

接口代码:

using System.Diagnostics;
using System.Management.Automation;
using System.Management.Automation.Runspaces;

public static ScriptResult Run2(string filePath, Dictionary<string,string> parameters)
{
    string myScript = File.ReadAllText(filePath);
    
    ScriptResult scriptResult = new ScriptResult();

    using (System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create())
    {
        ps.AddScript(myScript);

        foreach (var kvp in parameters)
        {
            ps.AddParameter(kvp.Key, kvp.Value);
        }

        var result = ps.Invoke();

        if (ps.HadErrors)
        {
            string errorMessage = "";

            foreach (var error in ps.Streams.Error)
            {
                errorMessage += error.ToString() + "\n"; <-- This is where I am getting the error message
            }

            throw new Exception(errorMessage);
        }

        foreach (var PSObject in result)
        {
            var x = PSObject.ToString();
        }
    }
    
    return scriptResult;
}

输出Get-ExecutionPolicy -List个:

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

注意:该脚本包含以下行:

Import-Module MicrosoftTeams

##script to get token##

Connect-MicrosoftTeams -AccessTokens @("$graphToken", "$teamsToken") | Out-Null

$getUserSettings = Get-CSOnlineUser -Identity $UserEmail -ErrorAction 'stop'

$output = @{
  UserConfig = $getUserSettings
}

$output | ConvertTo-JSON

Write-Output $output

PSVersionTable的输出

Name                           Value
----                           -----
PSVersion                      5.1.19041.4046
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.19041.4046
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

获取错误:

无法加载文件C:\Program Files\WindowsPowerShell\Modules\MicrosoftTeams\5.5.0\MicrosoftTeams.psm1,因为此系统上禁用了运行脚本.有关详细信息,请参阅About_Execution_Polures at https://go.microsoft.com/fwlink/?LinkID=135170.

推荐答案

Joel Coehoorn's helpful answer提供了这一谜题的关键部分:

  • 这意味着ASP.NET应用程序使用different用户标识运行,而不是将Unrestricted显示为其当前用户策略,并且该不同用户的当前用户策略显式设置为Restricted或(更有可能的是)not defined(Get-ExecutionPolicy -List报告为Undefined).

  • 在后一种情况下,有效的执行策略由LocalMachine范围定义;如果后者也是Undefined,则默认为Restricted,preventing脚本-文件执行-这就是您所看到的.

    • 注:如果执行策略由GPO(MachinePolicyUserPolicy)定义,则可以通过其他方式覆盖not.
    • 有关PowerShell执行策略的全面概述,请参见this answer.
  • PowerShell (Core) 7+ SDK项目中-与Windows PowerShell不同-独立PowerShell7+安装的LocalMachine策略对SDK项目是not可见的,因此从独立PowerShell会话运行时LocalMachine策略的值是irrelevant.但是,CurrentUser号策略is已看到并得到遵守.[1]

  • best solutionnot to rely on a preconfigured execution policy to begin with,而current process onlyuse an SDK method to set the execution policy dynamically,如下所示(这相当于使用Set-ExecutionPolicy -Scope Process Bypass -Force):

    // Create an initial default session state.
    var iss = InitialSessionState.CreateDefault2();
    
    // Set its script-file execution policy (for the current session (process) only).
    // 'Bypass' uncondtionally allows script execution.
    iss.ExecutionPolicy = Microsoft.PowerShell.ExecutionPolicy.Bypass;
    
    // Create a PowerShell instance with a runspace based on the 
    // initial session state and run a sample script to show
    // that the process-level Bypass policy took effect.
    using (PowerShell ps = PowerShell.Create(iss))
    {
      Console.WriteLine(
        ps.AddScript(@"Get-ExecutionPolicy -List | Out-String").Invoke()[0]
      );
    }
    

[1] Windows PowerShell stores its (non-GPO) execution policies in a fixed location in the registry, whereas PowerShell 7+ uses powershell.config.json files. For the LocalMachine scope, this file is stored alongside the PowerShell executable, which for SDK projects is not the home directory of any stand-alone PowerShell 7+ installation (which may or may not be present, and can hypothetically be installed anywhere), but the directory of the SDK project's own executable, as reflected in the PSHOME environment variable. By contrast, the CurrentUser-scope powershell.config.json is seen and honored by SDK projects, because it is stored in an installation-independent, fixed directory relative to the user's home directory. Specifically, the CurrentUser policy is stored in "$([Environment]::GetFolderPath('MyDocuments'))/powershell/powershell.config.json", and the LocalMachine one in "$PSHOME\powershell.config.json" (with $PSHOME having different meanings in stand-alone PowerShell vs. SDK projects).
Note that this means that while you could hypothetically bundle a powershell.config.json file with your project with a preconfigured policy, it could still be preempted by a CurrentUser policy from a stand-alone installation. Only the dynamic, per-process policy override shown in the next bullet point can prevent that (except, as noted, if GPOs control the execution policy).

Csharp相关问答推荐

在包含空项的列表上使用具有断言T的摘要表

Unity如何在PlayerPrefs中保存数据?

LINQ无法翻译SQLFunctions方法

TDLib与机器人共享电话号码

==和Tuple对象的相等<>

使用命令初始化可绑定属性

如何注销Microsoft帐户?

Polly v8—使用PredicateBuilder重试特定的状态代码

选取器与.NET Maui MVVM的绑定属性

注册所有IMediatR类

为什么Regex.IsMatch(";\\t";,";\\t";)返回FALSE而不是TRUE?

EFR32BG22 BLE在SPP模式下与PC(Windows 10)不连接

如何防止Visual Studio断点以红色突出显示到整行?

Google OAuth令牌交换在.Net中不起作用

如何更改新创建的实例的变量?

当`JToken?`为空时?

无法向Unity注册Microsoft Logger

SignalR跨域

为什么INTEGER在通过反射调用时对空对象返回TRUE,而在INTEGER上调用时返回FALSE?

现在是否有一个.NET SDK等效于AsyncEx的AsyncLock?