You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core API控制器执行PowerShell脚本调用Connect-AzAccount报错求助

问题

使用Microsoft.PowerShell.SDK与Microsoft.WSMan.Management 7.4.0编写的PowerShell脚本,在Visual Studio Code及ASP.NET Core API单元测试中执行正常,但在API控制器中调用时,执行Connect-AzAccount命令触发以下错误:

System.ArgumentNullException: Entry point was not found. Could not find tenant id for provided tenant domain 'yyyyyyyyyyyyyyyy'. Please ensure that the provided service principal 'xxxxxxxxxxxxxxx' is found in the provided tenant domain. ---> System.EntryPointNotFoundException: Entry point was not found. at System.Threading.Tasks.Sources.IValueTaskSource`1.GetStatus(Int16 token)

相关代码

PowerShell脚本(ps1):

$ApplicationId = "xxxxxxxxxxxxxxxxxxxx"
$TenantId = "yyyyyyyyyyyyyyyyyyyyyyyyy"
$ClientSecret = "zzzzzzzzzzzzzzzzzzzzzzzz"
$Credential = New-Object -TypeName "System.Management.Automation.PSCredential" -ArgumentList $ApplicationId, (ConvertTo-SecureString -String $ClientSecret -AsPlainText -Force)
Connect-AzAccount -ServicePrincipal -Credential $Credential -Tenant $TenantId
$token = (Get-AzAccessToken -ResourceUrl 'https://management.azure.com').Token
Write-Output $token

C#执行PowerShell脚本方法:

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

public async Task<PSDataCollection<PSObject>> ExecutePsFile(string path, Dictionary<string, string> parameters = null)
{
    using (var ps = PowerShell.Create())
    {
        ps.AddScript(path);
        var results = await  ps.InvokeAsync();
        var errors = ps.Streams.Error;

        if (errors.Count > 0)
        {
            var e = errors[0].Exception;
            ps.Streams.ClearStreams();
            throw e;
        }
        return results;
    }
}

排查与解决方案

  • 版本兼容性修复:EntryPointNotFoundException多由依赖库版本冲突导致。检查项目NuGet包,确保System.Threading.Tasks.Extensions等System.*系列包版本与PowerShell SDK 7.4.0依赖的版本完全对齐,消除版本差异。
  • 显式配置PowerShell运行空间:API控制器运行在隔离环境中,可能无法自动加载Az模块。创建PowerShell实例时显式导入所需模块:
    var initialSessionState = InitialSessionState.CreateDefault();
    initialSessionState.ImportPSModule(new[] { "Az.Accounts" });
    using (var ps = PowerShell.Create(initialSessionState))
    {
        // 原有执行逻辑
    }
    
  • 验证运行环境权限与配置:API运行身份(如IIS应用池身份)需具备访问Azure AD的网络权限,同时确保脚本中使用的租户ID、服务主体ID、密钥在API运行环境中能正确读取(建议改用配置文件/环境变量传递,避免硬编码)。
  • 异步调用上下文排查:尝试改用同步调用测试是否正常:
    var results = ps.Invoke();
    
    若同步调用正常,在异步代码中添加ConfigureAwait(false)避免上下文死锁:
    var results = await ps.InvokeAsync().ConfigureAwait(false);
    
  • 统一Az模块版本:确保API运行环境安装的Az模块版本与VS Code/单元测试环境一致,可在脚本开头指定模块版本:
    Import-Module Az.Accounts -RequiredVersion 2.12.0 # 替换为测试通过的版本
    

内容的提问来源于stack exchange,提问作者Vinh Ngo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 17:20:10