当我使用 Microsoft.PowerShell.SDK 库和 Microsoft.WSMan.Management 版本 7.4.0 在 Visual Studio Code 上运行下面的 Powershell 脚本并在 Asp.net Core API 上进行单元测试时。它工作正常。
但是当我从 Asp.net core Api 的 Api 控制器运行这个 Powershell 脚本时。当调用脚本的 Connect-AzAccount 命令时,它会引发错误。您能否查看下面的代码和错误消息以支持我解决问题?谢谢!
错误信息:
“System.ArgumentNullException:找不到入口点。无法 查找提供的租户域“yyyyyyyyyyyyyyyy”的租户 ID。请 确保找到提供的服务主体“xxxxxxxxxxxxxxx” 在提供的租户域中。 ---> System.EntryPointNotFoundException:未找到入口点。在 System.Threading.Tasks.Sources.IValueTaskSource`1.GetStatus(Int16 令牌)”
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;
}
}
未找到入口点。找不到提供的租户域“yyyyyyyyyyyyyyy”的租户 ID。请确保在提供的租户域中找到提供的服务主体“xxxxxxxxxxxxxxx”。 --->
出现上述错误可能是由于 Az 模块与 Az.Accounts 模块版本不兼容所致。
在我的环境中,我安装了具有较新版本的 Az 模块,例如
Az =11.1.0
和 Az.Accounts=2.15.0
命令:
Install-Module -Name Az -RequiredVersion 11.1.0 -AllowClobber
现在,我使用
Get-InstalledModule
命令检查已安装的模块。
输出:
PS C:\Windows\system32> Get-InstalledModule
Version Name Repository Description
------- ---- ---------- -----------
11.1.0 Az PSGallery Microsoft Azure PowerShell - Cmdlets to manage resources in ...
2.15.0 Az.Accounts PSGallery Microsoft Azure PowerShell - Accounts credential management ...
现在,如果我在我的环境中用 C# 运行相同的代码,我可以通过服务主体获取令牌。
$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
输出:
参考: