日期:2014-05-18  浏览次数:20923 次

C# 调用powershell 相互操作
首先我们来写一个C#调用powershell的公共方法
 
需要引用:System.Management.Automation.dll
 
此dll一般装上powershell 的sdk就可以找到
 
我这里直接放到源码里了。。
 
折叠展开C# 代码

  1. using System.Management;  
  2. using System.Management.Automation;  
  3. using System.Management.Automation.Runspaces;  

执行脚本代码如下:
 
折叠展开C# 代码

  1. /// <summary>  
  2. /// PowerShell脚本基础  
  3. /// </summary>  
  4. public static class PowerShell  
  5. {  
  6. /// <summary>  
  7. /// 运行脚本信息,返回脚本输出  
  8. /// </summary>  
  9. /// <param name="scriptText"& gt;需要运行的脚本</param>  
  10. /// <returns>output of the script</returns>  
  11. public static string RunScript(List<string> scripts,List<PSParam> pars)  
  12. {  
  13. Runspace runspace = RunspaceFactory.CreateRunspace();  
  14.  
  15. runspace.Open();  
  16.  
  17. Pipeline pipeline = runspace.CreatePipeline();  
  18. foreach (var scr in scripts)  
  19. {  
  20. pipeline.Commands.AddScript(scr);  
  21. }  
  22.  
  23. //注入参数  
  24. if (pars != null)  
  25. {  
  26. foreach (var par in pars)  
  27. {  
  28. runspace.SessionStateProxy.SetVariable(par.Key,par.Value);  
  29. }  
  30. }  
  31.  
  32. //返回结果  
  33. var results = pipeline.Invoke();  
  34. runspace.Close();  
  35. StringBuilder stringBuilder = new StringBuilder();  
  36. foreach (PSObject obj in results)  
  37. {  
  38. stringBuilder.AppendLine(obj.ToString());  
  39. }  
  40. return stringBuilder.ToString();  
  41. }  
  42. }  
  43.  
  44. /// <summary>  
  45. /// 脚本参数  
  46. /// </summary>  
  47. public class PSParam  
  48. {  
  49. public string Key  
  50. {  
  51. get;  
  52. set;  
  53. }  
  54.  
  55. public object Value  
  56. {  
  57. get;  
  58. set;  
  59. }  
  60. }  

 
这句为注入脚本一个.net对象:runspace.SessionStateProxy.SetVariable(par.Key,par.Value);  
 
这样在powershell脚本中就可以直接通过$key访问和操作这个对象
 
下面来看调用实例:
 
定义一个.net对象,以便powershell中调用:
折叠展开C# 代码

  1. class info  
  2. {  
  3. public int x { get; set; }  
  4. public int