使用 C# 执行 Powershell 命令 (azureVM)

Using C# to execute Powershell command (azureVM)

我正在尝试开发一个 .Net 表单应用程序以使用 Powershell cmdlet 在 C# 中管理 azure VM。我必须使用 Azure 模块才能正常工作。

其中一个 cmdlet 将是 Add-AzureAccount

我的问题是如何在 C# 项目中包含此模块 (Azure)?

我们可以使用 PowerShell cmdlets Import-module 将相应的模块添加到当前会话。我们可以使用强制参数 re-import 一个模块进入同一个会话。
Import-module -name azure -force

导入的东西是导入的模块需要安装在本地计算机或远程计算机上。因此,如果我们想要从 C# 项目执行 Azure PowerShell cmdlet,我们需要确保安装了 Azure PowerShell。我们可以使用 install-module AzureRM 或 Azure 更多详细信息请参考 Get Started Azure PowerShell cmdlets。在 Azure VM 中,默认安装 Azure PowerShell。 关于如何使用C#调用PowerShell命令或PS1文件请参考Prageeth Saravanan提到的link or another SO Thread.

在评论部分,@Prageeth Saravanan 提供了一个有用的 link 关于如何在 C# 中集成 PowerShell。

https://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/

快速示例:

首先我必须包括这些参考文献:

System.Management.Automation
System.Collections.ObjectModel

注意:您需要为 "Management.Automation" 添加 NuGet 包。只需输入 "System.Management.Automation" 即可找到。

C#代码:

//The first step is to create a new instance of the PowerShell class
using (PowerShell powerShellInstance = PowerShell.Create()) //PowerShell.Create() creates an empty PowerShell pipeline for us to use for execution.
{   
 // use "AddScript" to add the contents of a script file to the end of the execution pipeline.
 // use "AddCommand" to add individual commands/cmdlets to the end of the execution pipeline.

    powerShellInstance.AddScript("param($param1) $d = get-date; $s = 'test string value'; $d; $s; $param1; get-service");

    // use "AddParameter" to add a single parameter to the last command/script on the pipeline.
    powerShellInstance.AddParameter("param1", "parameter 1 value!");

    //Result of the script with Invoke()
    Collection<PSObject> result = powerShellInstance.Invoke();

    //output example : @{yourProperty=value; yourProperty1=value1; yourProperty2=StoppedDeallocated; PowerState=Stopped; OperationStatus=OK}}

    foreach (PSObject r in result)
    {
        //access to values
        string r1 = r.Properties["yourProperty"].Value.ToString();
    }
}

希望对您有所帮助!