如何从 Azure 函数(Dotnet 核心)中的 PowerShell 脚本 运行 获取 Connect-AzureAD 的 TenantId?

How to get TenantId of Connect-AzureAD from PowerShell Script running in Azure function (Dotnet Core)?

我正在尝试从 Connect-AzureAD 获取将在 powershell 脚本中返回的 TenantId。

下面是 powershell 脚本:

Install-Module -Name AzureAD
$User = "test@domain.onmicrosoft.com"
$PWord = ConvertTo-SecureString -String "password" -AsPlainText -Force
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, $PWord
$context = Connect-AzureAD -Credential $credential
$tenantId = $context.TenantId.Guid.ToString()
[pscustomobject]@{
    user = $tenantId
}

该脚本在单独作为 PowerShell 脚本执行时有效。但是,当我在dotnet core中尝试运行时,它似乎是空的。

public static string RunScript()
        {
            using (Runspace myRunSpace = RunspaceFactory.CreateRunspace())
            {
                myRunSpace.Open();
                using (PowerShell ps = PowerShell.Create())
                {
                    var imagePath = Path.Combine(Environment.CurrentDirectory, @"Resources", "ConnectAzureAD.ps1");
                    string content = File.ReadAllText(imagePath);

                    ps.AddScript(content);
                    var piplineObjs = ps.Invoke();
                    StringBuilder stringBuilder = new StringBuilder();
                    stringBuilder.AppendLine(piplineObjs.Count.ToString());
                    foreach (PSObject obj in piplineObjs)
                    {
                        stringBuilder.AppendLine(obj.Properties["user"].Value.ToString());
                    }


                    return stringBuilder.ToString();
                }
            }

        }

我收到以下错误:

System.Private.CoreLib: Exception while executing function: Object reference not set to an instance of an object.

上述函数是从 Azure 函数调用的。它正在使用 Microsoft.PowerShell.SDK v6.2.7 和 System.Management.Automation v6.2.7.

如何获取从 dotnet core 中的 powershell 脚本返回的租户 ID? 或者我如何使用仅包含用户电子邮件和密码的代码获取租户 ID?

谢谢!

您可以通过请求获取租户ID this 图api:https://graph.microsoft.com/v1.0/organization

在api的响应中,我们可以在其中找到id(即租户id):