最近,隨著System Center Virtual Machine Management 2012 SP1 的發(fā)布,越來越多的人,加入到私有云的開發(fā)中來,特別是,開發(fā)測試云,但國內(nèi)的技術文檔及資料相當匱乏。前幾天,一個外地的同事在問 “怎么用C# 調(diào)用PowerShell并且取得返回值”的問題。
解決方案如下:
調(diào)用系統(tǒng)的PowerShell,可以用:
////// invoke system powershell /// /// public static void InvokeSystemPS(string cmd) { Listps = new List (); ps.Add("Set-ExecutionPolicy RemoteSigned"); ps.Add("Set-ExecutionPolicy -ExecutionPolicy Unrestricted"); ps.Add("& " + cmd); Runspace runspace = RunspaceFactory.CreateRunspace(); runspace.Open(); Pipeline pipeline = runspace.CreatePipeline(); foreach (var scr in ps) { pipeline.Commands.AddScript(scr); } pipeline.Invoke();//Execute the ps script runspace.Close(); }
2.調(diào)用VMM產(chǎn)品,這里以“Get-VM -Name vm001” 為例:
////// Invoke VMM Poershell /// public static void InvokeVMMPS() { RunspaceConfiguration rconfig = RunspaceConfiguration.Create(); PSSnapInException Pwarn = new PSSnapInException(); Runspace runspace = RunspaceFactory.CreateRunspace(); string test = "Import-Module VirtualMachineManager\r\n"; runspace = RunspaceFactory.CreateRunspace(rconfig); runspace.Open(); Pipeline pipeline = runspace.CreatePipeline(); pipeline.Commands.AddScript(test); try { var results = pipeline.Invoke(); using (Pipeline pipe = runspace.CreatePipeline()) { //Get-VM -Name vm001 Command cmd = new Command("Get-VM"); cmd.Parameters.Add("Name", "vm001"); pipe.Commands.Add(cmd); var result = pipe.Invoke(); } } catch (Exception ex) { throw ex; } }
Firstly, you need to add reference "System.Management.Automation". Then, add two name space:
using System.Management.Automation.Runspaces;
using System.Management.Automation;
Powershell 3.0作為Windows Management Framework 3.0的一部分,集中體現(xiàn)了Powershell 3.0的新特性:Powershell工作流、增強會話災難恢復、語法簡潔方便、增強了cmdlet的查找和自動導入模塊的功能、提供了對webservice強大支持和ISE命令加載項等。
Powershell需要用到.NET框架和cmdlets命令集。作為PowerShell的用戶,可以使用系統(tǒng)自帶的cmdlets,也可以自定義cmdlets,擴展實現(xiàn)更強大的功能。而且,PowerShell使用了面向?qū)ο蠓椒,基?Net,這是VBScript所不能提供或者支持的。