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. windows phone 模拟器

    window phone 模拟器启动报错 修改Bios设置,我的是yoga pro 2,只修改 即可.启动成功

  2. Fiddler屏蔽某些url的抓取方法

    在用Fiddler调试网页的时候,可能某些频繁的ajax轮询请求会干扰我们,可以通过以下方法屏蔽某些url的抓取. 在需要屏蔽的url行上右键---->“Filter Now”-----> ...

  3. js 将一大段时间均分为很多个小时间段

    最近写项目,遇到一个将选中时间段平均分割为若干小段,然后根据小段时间在数据库查询求均值的问题,后台大哥犯懒,非说后台做不了,让我分好传给他ヾ(. ̄□ ̄)ツ゜゜゜好气呦,但还要保持微笑,我就是这么懂礼貌 ...

  4. C语言/原子/编译,你真的明白了吗?

    说到原子,类似于以下的代码可能人人都可以看出猫腻. #include <stdio.h> #include <pthread.h> ; void* mythread(void* ...

  5. NodeJS 初学之安装配置环境

    [TOC] 1.环境安装 操作系统: Ubuntu 16.04.2 LTS 1.1安装nvm ryan@ryan-900X5L:~/temp$ curl https://raw.githubuserc ...

  6. jquery各种事件使用方法总结(from:天宇之游)

    ps:本博客转自博主  天宇之游 ,地址:http://www.cnblogs.com/cwp-bg/  ,再次感谢天宇之游.jquery事件使用方法总结 一.鼠标事件1. click():鼠标单击事 ...

  7. 【转载】CSS3 filter:drop-shadow滤镜与box-shadow区别应用

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

  8. LINUX 笔记-文本过滤

    ^                        只匹配行首 $                       只匹配行尾 *                        一个单字符后紧跟*,匹配0个 ...

  9. Servlet 笔记-Cookie 处理

    Cookie 是存储在客户端计算机上的文本文件,并保留了各种跟踪信息. 识别返回用户包括三个步骤: 服务器脚本向浏览器发送一组 Cookie.例如:姓名.年龄或识别号码等. 浏览器将这些信息存储在本地 ...

  10. Spring源码情操陶冶-AOP之ConfigBeanDefinitionParser解析器

    aop-Aspect Oriented Programming,面向切面编程.根据百度百科的解释,其通过预编译方式和运行期动态代理实现程序功能的一种技术.主要目的是为了程序间的解耦,常用于日志记录.事 ...