如何让C#快速执行PowserShell的脚本
2010-11-09 13:10:29 来源:WEB开发网核心提示:步骤如下:<1>前提:安装PowerShell SDK.要在C#执行Power Shell 脚本.需要在PowerShell的SDK添加相关引用. Windows 7系统自动集成Windows PowerShell 2.0版本.如果尚未请点击下载安装<2>新建Console Applicatio
步骤如下:
<1>前提:安装PowerShell SDK.
要在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 下找到:

添加相关引用:
//导入引入 using System.Management.Automation; using System.Management.Automation.Runspaces; using System.Management; using CallPowerShellDemo.EntityModel;
执行脚本方法:
Main方法中调用:
static void Main(string[] args)
{
Console.WriteLine("请输入你要执行的PowserShell命名:");
string gettakeresult=Console.ReadLine();
//Main Method Get All Process
List<string> getshellcmdlist = new List<string> ();
List<EntityModel.ShellParameter> getpatalist = new List<ShellParameter>
{
new ShellParameter{ ShellKey="Name",ShellValue="QQ*"}
};
if (!string.IsNullOrEmpty(gettakeresult))
{
getshellcmdlist.Add(gettakeresult);
}
//Execu Cmd
string getresult=Program.ExecuteShellScript(getshellcmdlist,getpatalist);
//Output ExecuteResult 22: Console.WriteLine("执行结果:");
Console.WriteLine(getresult);
}
执行结果: 获取以Ca作为开头名称系统进程信息 ShellScript :get-process Ca*
则利用PowerShell脚本轻松获取进程名称以Ca开头所有进程名称. 类似我们轻松在获取360在本地系统详细的版本信息: get-process 360* –fileversioninfo


封装参数实体:
/// <summary>
/// 定义一个封装Shell脚本命令参数实体类
/// Author:chenkai Date:2010年11月9日10:27:55
/// </summary>
public class ShellParameter
{
public string ShellKey { get; set; }
public string ShellValue { get; set; }
}
[]
更多精彩
赞助商链接