C#执行PowserShell 脚本

时间:2023-12-21 22:59:32

Windows PowserShell能够很简洁 快速通过Script脚本方式获得我们想要执行效果. 如何在C#中任意执行PowerShell脚本.?类似目前我要在做一个进程管理工具. 通过PowerShell脚本方式获取当前系统进程调用的详细信息. C#如何执行Shell Script:

步骤如下:

<1>前提:安装PowerShell SDK. Selenium

要在C#执行Power Shell 脚本.需要在PowerShell的SDK添加相关引用. Windows 7系统自动集成Windows PowerShell 2.0版本.如果尚未请点击下载安装

<2>新建Console Application项目 命名:CallPowerShellDemo .添加引用:System.Management.Automation 这个命名空间需要引用PowerShell SDK中System.Management.Automation.dll. 如果已经PowerShell SDK可以在目录:C:\Program Files\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0 下找到:

添加相关引用:

   1:  //导入引入
   2:  using System.Management.Automation;
   3:  using System.Management.Automation.Runspaces;
   4:  using System.Management;
   5:  using CallPowerShellDemo.EntityModel;

封装参数实体:

   1:   /// <summary>
   2:  /// 定义一个封装Shell脚本命令参数实体类
   3:  /// Author:chenkai Date:2010年11月9日10:27:55
   4:  /// </summary>
   5:  publicclass ShellParameter
   6:      {
   7:  public string ShellKey { get; set; }
   8:  public string ShellValue { get; set; }
   9:      }

执行脚本方法:

/// <summary>
/// 执行PowserShell 脚本核心方法
/// </summary>
/// <param name="getshellstrlist">Shell脚本集合</param>
/// <param name="getshellparalist">脚本中涉及对应参数</param>
/// <returns>执行结果返回值</returns>
public static string ExecuteShellScript(List<string> getshellstrlist, List<ShellParameter> getshellparalist)
 
    string getresutl = null;
    try
    
        //Create Runspace
        Runspace newspace = RunspaceFactory.CreateRunspace();
        Pipeline newline = newspace.CreatePipeline();
 
        //open runspace
        newspace.Open();
 
        if (getshellstrlist.Count > 0)
        
            foreach (string getshellstr in getshellstrlist)
            
                //Add Command ShellString
                newline.Commands.AddScript(getshellstr);
            
        
 
        //Check Parameter
        if (getshellparalist != null && getshellparalist.Count > 0)
        
            int count = 0;
            foreach (EntityModel.ShellParameter getshellpar in getshellparalist)
            
                //Set parameter
                //newspace.SessionStateProxy.SetVariable(getshellpar.ShellKey,getshellpar.ShellValue);
                CommandParameter cmdpara = new CommandParameter(getshellpar.ShellKey, getshellpar.ShellValue);
                newline.Commands[count].Parameters.Add(cmdpara);
            
        
 
        //Exec Restult
        var getresult = newline.Invoke();
        if (getresult != null)
        
            StringBuilder getbuilder = new StringBuilder();
            foreach (var getresstr in getresult)
            
                getbuilder.AppendLine(getresstr.ToString());
            
            getresutl = getbuilder.ToString();
        
    
    catch (Exception se)
    
        //catch Excetption 
    
    return getresutl;
}

Main方法中调用:

   1:  static void Main(string[] args)
   2:          {
   3:              Console.WriteLine("请输入你要执行的PowserShell命名:");
   4:  string gettakeresult=Console.ReadLine();
   6:  //Main Method Get All Process
   7:              List<string> getshellcmdlist = new List<string> ();
   8:              List<EntityModel.ShellParameter> getpatalist = new List<ShellParameter> 
   9:              {
  10:  new ShellParameter{ ShellKey="Name",ShellValue="QQ*"}
  11:              };
  14:  if (!string.IsNullOrEmpty(gettakeresult))
  15:              {
  16:                  getshellcmdlist.Add(gettakeresult);
  17:              }
  18:  //Execu Cmd
  19:  string getresult=Program.ExecuteShellScript(getshellcmdlist,getpatalist);
  21:  //Output ExecuteResult
  22:              Console.WriteLine("执行结果:");
  23:              Console.WriteLine(getresult);
  24:          }

执行结果: 获取以Ca作为开头名称系统进程信息 ShellScript :get-process Ca*

则利用PowerShell脚本轻松获取进程名称以Ca开头所有进程名称. 类似我们轻松在获取360在本地系统详细的版本信息: get-process 360* –fileversioninfo