C# 调用PowerShell方法

PowerShell应为编写和运行都很方便,所以为了重复利用,经常写了一些小方法或者PS代码片段。使用的时候可能会很难找到自己想要的那个方法,如果要是有一个界面把这些代码管理起来并且调用,那就很爽了

1.创建一个powershell的方法,供C#调用,方法很简单,两个数的加法运算

1 function Sum
2 {
3 param([int]$first, [int]$second)
4 $result = $first + $second
5 return $result
6 }

 

 2. 在C#的控制台程序中创建一个私有方法,调用powershell

首先定义一个powershell存放路径的全局变量

 1 private static string script =File.ReadAllText(@"Path\Sum.ps1");
 2 private static void CallPS1()
 3 {
 4     using (Runspace runspace = RunspaceFactory.CreateRunspace())
 5         {
 6          runspace.Open();
 7 
 8          PowerShell ps = PowerShell.Create();
 9          ps.Runspace = runspace;
10          ps.AddScript(script);
11          ps.Invoke();
12 
13          ps.AddCommand("Sum").AddParameters(
14 
15              new Dictionary<string, int>()
16              {
17                  {"first", 5},
18                  {"second", 4}
19              }
20          );
21 
22          foreach (PSObject result in ps.Invoke())
23          {
24              Console.WriteLine("CallPS1()");
25              Console.WriteLine(result);
26          }
27 
28 }
29 
30         }

 

调用方法需要添加一个引用System.Management.Automation.dll
如果找不到可以到这个路径下找到:C:\windows\assembly\GAC_MSIL\System.Management.Automation\1.0.0.0__31bf3856ad364e35\System.Management.Automation.dll

posted @ 2013-06-13 09:03  CodingStar  阅读(11288)  评论(2编辑  收藏  举报