2017-01-23 113 views
0

我正在嘗試開發一個.Net窗體應用程序,以使用Powershell cmdlet在C#中管理azure虛擬機。我必須使用Azure模塊才能正常工作。使用C#執行Powershell命令(azureVM)

其中的cmdlet的將被添加-AzureAccount

我的問題是我怎麼能包括這個模塊(天青)在C#項目?

+5

您將不得不創建一個PS腳本並從C#中調用它。請參閱https://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/ –

+0

您有關於此主題的任何更新嗎? –

+0

我剛剛發佈了answert @ TomSun-MSFT –

回答

1

在評論部分,@Prageeth Saravanan介紹瞭如何在C#中集成PowerShell的有用鏈接。

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

快速例如:

首先,我必須包括這些裁判:

System.Management.Automation 
System.Collections.ObjectModel 

注:您需要添加一個NuGet包的 「Management.Automation」 。只需輸入「System.Management.Automation」即可找到它。

C#代碼:

//The first step is to create a new instance of the PowerShell class 
using (PowerShell powerInstance = 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 = powerInstance.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(); 
        } 
       } 

希望這有助於!

3

我們可以使用PowerShell cmdlet Import-module爲當前會話添加相應的模塊。我們可以使用強制參數將模塊重新導入到同一個會話中。
Import-module -name azure -force

導入的東西是導入的模塊需要安裝在本地計算機或遠程計算機上。因此,如果我們想從C#項目執行Azure PowerShell cmdlet,那麼我們需要確保安裝了Azure PowerShell。我們可以使用安裝模塊AzureRM或Azure更多的細節請參考Get Started Azure PowerShell cmdlets。在Azure虛擬機中,默認情況下安裝Azure PowerShell。 關於如何使用C#調用PowerShell命令或PS1文件,請參閱Prageeth Saravanan提到的link或另一個SO Thread