轉(zhuǎn)帖|其它|編輯:郝浩|2011-09-19 14:34:05.000|閱讀 1199 次
概述:本文主要講述如何在C#中執(zhí)行PowerShell 腳本,希望對(duì)大家有幫助。
# 界面/圖表報(bào)表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
在C#中調(diào)用powershell腳本,需要引用的namespace如下:
using System.Management.Automation;
using System.Management.Automation.Runspaces;
添加System.Management.Automation.dll的引用,需要使用瀏覽,如果不知道位置,可以先在本機(jī)查找下。
代碼如下:
1 //RunPowershell(@".\x.ps1", "");
2 private Collection<PSObject> RunPowershell(string filePath, string parameters)
3 {
4 RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
5 Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
6 runspace.Open();
7 RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
8 Pipeline pipeline = runspace.CreatePipeline();
9 Command scriptCommand = new Command(filePath);
10 Collection<CommandParameter> commandParameters = new Collection<CommandParameter>();
11
12 string[] tempParas = parameters.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
13 for (int i = 0; i < tempParas.Length; i += 2)
14 {
15 CommandParameter commandParm = new CommandParameter(tempParas[i], tempParas[i + 1]);
16 commandParameters.Add(commandParm);
17 scriptCommand.Parameters.Add(commandParm);
18 }
19
20 pipeline.Commands.Add(scriptCommand);
21 Collection<PSObject> psObjects;
22 psObjects = pipeline.Invoke();
23
24 if (pipeline.Error.Count > 0)
25 {
26 throw new Exception("腳本執(zhí)行失敗");
27 }
28
29 runspace.Close();
30
31 return psObjects;
32 }
powershell腳本執(zhí)行的結(jié)果存在Collection<PSObject>集合中。
本站文章除注明轉(zhuǎn)載外,均為本站原創(chuàng)或翻譯。歡迎任何形式的轉(zhuǎn)載,但請(qǐng)務(wù)必注明出處、不得修改原文相關(guān)鏈接,如果存在內(nèi)容上的異議請(qǐng)郵件反饋至chenjj@fc6vip.cn
文章轉(zhuǎn)載自:網(wǎng)絡(luò)轉(zhuǎn)載