在发布后事件中运行的程序中使用Connect-AzureRmAccount登录到Azure Powershell

时间:2018-10-26 16:19:58

标签: c# visual-studio azure powershell msdeploy

我有一个使用以下代码的程序(简体)

        using (PowerShell powerInstance = PowerShell.Create()) 
        {

            powerInstance.AddScript("Set-ExecutionPolicy Unrestricted");


            powerInstance.AddScript("Connect-AzureRmAccount");
            powerInstance.Invoke();
        }

当显示登录弹出窗口以输入凭据时,此方法很好用。

现在,我希望在将Web应用程序发布为天蓝色后运行此程序,我在这样的单独Web项目中添加了一个发布后事件

  <Target Name="PostAzurePublish" AfterTargets="MSDeployPublish">
   <Exec Command="C:\MyProgram.exe"></Exec>  
  </Target>

这里的问题是,当我发布Web应用程序时,运行powershell命令的程序会运行但无限期挂起,并且不会显示“登录”弹出窗口。因此,我假设它只是在等待提供凭据,但是因为从未显示登录对话框挂起。

在这种情况下,有没有一种简单的方法可以使“登录”对话框显示出来?

1 个答案:

答案 0 :(得分:0)

您可以使用Connect-AzureRmAccount PowerShell命令,而无需进行交互式登录。您只需使用服务主体作为登录凭据。

$applicationId = "<service prinicple application id>";
$securePassword = "<service prinicple password>" | ConvertTo-SecureString -AsPlainText -Force
$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $applicationId, $securePassword
Connect-AzureRmAccount -ServicePrincipal -Credential $credential -TenantId "<your tenantid>"

查看我的详细答案here