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

C#执行PowserShell 脚本的更多相关文章

  1. 【转】linux 定时执行shell脚本

    在oracle 中可以利用dbms_job包定时执行pl/sql.sql过程,在像备份等需要在操作系统级定时任务只能采用crontab来完成 本文讲述crontab具体用法,以供备忘. 在oracle ...

  2. AngularJs中,如何在render完成之后,执行Js脚本

    AngularJs是Google开源的前端JS框架.使用AngularJs, 我们能够容易地.健壮的开发出类似于Gmail一样的单页Web应用.AngularJs这个新兴的MVC前端框架,具有以下特点 ...

  3. crontab不执行perl脚本分析

    在新装的Linux服务器上部署了一个作业监控磁盘空间并提前告警,在shell脚本里面调用了一个perl脚本发送告警邮件.结果出现了一个很奇怪的现象:如果手工执行该脚本/home/oracle/scri ...

  4. SQL Server自动化运维系列——批量执行SQL脚本(Power Shell)

    需求描述 一般在生产环境中,在投产的情况下,需要批量的来执行SQL脚本文件,来完成整个投产,如果投产文件比较多的情况下,无疑这是一个比较痛苦的过程,所以本篇通过PowerShell脚本来批量完成. 监 ...

  5. jeecg安装——mysql数据库创建+手动执行初始化脚本

    国产的开源项目官方文档写得那么详细,已经是很厚道了,可惜俺这种菜鸟还是会碰到各种"小"问题,做个笔记先! 1.新建数据库: CREATE DATABASE jeecg DEFAUL ...

  6. win7计划任务执行php脚本方法

    第一步:编写bat文件 方法1:php方法 方法2:exploere浏览器 电脑上新建一个txt文本,把代码放进去.然后把他另存为xxx.bat explorer "http://网址/e/ ...

  7. 动态执行python脚本

    前言 存在许多独立的python脚本,这些脚本可能会增加,也可能会减少,现在需要按照某种顺序调度这些程序.在python的standard library中,有一个模块imp可以实现动态的调用ptho ...

  8. shell中创建mysql库和执行sql脚本

    以前执行oracle脚本都是放到plsql中执行 mysql 脚本执行: (1).先创建一个worlddb库 (2).导入sql脚本: 这就ok啦,哈哈.

  9. Linux中执行shell脚本的4种方法总结

    bash shell 脚本的方法有多种,现在作个小结.假设我们编写好的shell脚本的文件名为hello.sh,文件位置在/data/shell目录中并已有执行权限. 方法一:切换到shell脚本所在 ...

随机推荐

  1. Ubuntu下的终端多标签切换快捷键

    ubuntu下由于常在终端下工作,也同样需要在一个终端窗口下开启多个标签方便日常开发工作(vim党,尽量避免使用鼠标) 方法一: alt+1 alt+2 alt+3 方法二: ctrl + pageU ...

  2. RTKLIB编译及RTCM数据读取样例

    1.RTKLIB简介 RTKLIB是全球导航卫星系统GNSS(global navigation satellite system)的标准&精密定位开源程序包,RTKLIB由日本东京海洋大学( ...

  3. Jquery添加和全部删除

    <html> <head> <meta charset="utf-8" /> <title></title> <s ...

  4. 【学习】ie8支持rgba()透明度颜色

    (我的博客网站中的原文:http://www.xiaoxianworld.com/archives/285,欢迎遇到的小伙伴常来瞅瞅,给点评论和建议,有错误和不足,也请指出.) rgba()函数可以用 ...

  5. 【转载】CSS font关键字属性值的简单研究

    文章转载自 张鑫旭-鑫空间-鑫生活 http://www.zhangxinxu.com/wordpress/ 原文链接:http://www.zhangxinxu.com/wordpress/?p=5 ...

  6. bzoj1812 [Ioi2005]riv

    riv 几乎整个Byteland王国都被森林和河流所覆盖.小点的河汇聚到一起,形成了稍大点的河.就这样,所有的河水都汇聚并流进了一条大河,最后这条大河流进了大海.这条大河的入海口处有一个村庄--名叫B ...

  7. Windows 10 16251 添加的 api

    本文主要讲微软最新的sdk添加的功能,暂时还不能下载,到 7月29 ,现在可以下载是 16232 ,支持Neon效果 实际上设置软件最低版本为 16232 就自动支持 Neon 效果. 主要添加了 A ...

  8. Windows 10「设置」应用完整MS-Settings快捷方式汇总

    分类 设置名称 快捷方式 系统 显示 ms-settings:display 通知和操作 ms-settings:notifications 平板电脑模式 ms-settings:tabletmode ...

  9. Developing Universal Windows Apps 开发UWA应用 问答

    开始是一些欢迎,就不翻译 Question: Is the code already there? Answer: There is some code on that codeplex site, ...

  10. 前端工程化grunt

    1.grunt是什么? grunt是基于nodejs的前端构建工具.grunt用于解决前端开发的工程问题. 2.安装nodejs Grunt和所有grunt插件都是基于nodejs来运行的. 安装了n ...