如何在 C# windows 应用程序中使用 azure 命令调用 PowerShell 脚本

How to call PowerShell script with azure commands in C# windows application

下面是我的活动,如果我通过简单的 powershell 脚本,它运行良好,但如果我通过的脚本包含任何 Azure 命令,则输出为空白。 (那个 azure 命令脚本在 powershell 命令提示符下 运行 没问题)

private void RunScript_Click(object sender, EventArgs e)
{
        string result = "";

        PSDataCollection<PSObject> myOutPut = new PSDataCollection<PSObject>();

        try
        {
            InitialSessionState initial = InitialSessionState.CreateDefault();
            initial.ImportPSModule(new string[] {
                        @"C:\Program Files\WindowsPowerShell\Modules\AzureRM.2.0\AzureRM.psd1",
                });

            using (Runspace objRunSpace = RunspaceFactory.CreateRunspace(initial))
            {
                objRunSpace.Open();

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

                    objPowerShell.Runspace = objRunSpace;

                    string Script = textBoxURL.Text;                        

                    objPowerShell.AddScript(Script);

                    objPowerShell.AddCommand("Out-String");

                    IAsyncResult IvokeResult = objPowerShell.BeginInvoke<PSObject, PSObject>(null, myOutPut);

                    while (IvokeResult.IsCompleted == false)
                    {
                        System.Threading.Thread.Sleep(100);
                    }

                    foreach (PSObject outitem in myOutPut)
                    {
                        result += outitem.ToString();
                    }
                }
            }

            textBoxOutPut.Text = result;
        }
        catch (Exception ex)
        {
        }
    }

你在哪里连接到 Azure?

您加载了模块,但没有建立与 Azure 的连接来使用 cmdlet。

在您的原生 PoSH instance/session 中,您需要这样才能工作:

# Set creds
$AdminCreds = Get-Credential -Credential 'admin@domain.com'

# Connect to Azure AD
Connect-AzureAD -Credential $Admincreds


Account                          Environment TenantId   TenantDomain            AccountType
-------                          ----------- --------   ------------            -----------
admin@contoso.onmicrosoft.com    AzureCloud  11...      contoso.onmicrosoft.com User     

否则,您最终会遇到这样的错误...

Get-AzureADApplication
Get-AzureADApplication : You must call the Connect-AzureAD cmdlet before calling any other cmdlets.
At line:1 char:1
+ Get-AzureADApplication
+ ~~~~~~~~~~~~~~~~~~~~~~

根据我的测试,您提到的代码没有问题。如果输入错误的命令,我会得到空输出。所以请确保你的命令是正确的。

另一个重要的事情是确保它有输出的命令。我测试了 azure 命令 Add-AzureRmAccount.