繁体   English   中英

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

[英]Using C# to execute Powershell command (azureVM)

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

该cmdlet之一将是Add-AzureAccount

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

我们可以使用PowerShell cmdlet 导入模块将相应的模块添加到当前会话。 我们可以使用force参数将模块重新导入到同一会话中。
Import-module -name azure -force

导入的事情是导入的模块需要安装在本地计算机或远程计算机上。 因此,如果我们要从C#项目执行Azure PowerShell cmdlet,则需要确保已安装Azure PowerShell。 我们可以使用安装模块AzureRM或Azure更多详细信息,请参阅Azure Azure PowerShell cmdlet入门 在Azure VM中,默认情况下会安装Azure PowerShell。 有关如何使用C#调用PowerShell命令或PS1文件的信息,请参阅Prageeth Saravanan提到的链接或另一个SO Thread

在评论部分,@ Prageeth Saravanan提供了有关如何将PowerShell集成到C#中的有用链接。

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();
    }
}

希望这可以帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM