C#中执行PowerShell 脚本

来源:互联网 发布:汽车进出口数据 编辑:程序博客网 时间:2024/05/17 11:32

在C#中调用powershell脚本,需要引用的namespace如下:

using System.Management;  

using System.Management.Automation;  

using System.Management.Automation.Runspaces; 

添加System.Management.Automation.dll的引用,需要使用浏览,如果不知道位置,可以先在本机查找下。

/// <summary>   
/// PowerShell脚本基础   
/// </summary>   
public static class PowerShell   
{   
    /// <summary>   
    /// 运行脚本信息,返回脚本输出   
    /// </summary>   
    /// <param name="scriptText">需要运行的脚本</param>   
    /// <returns>output of the script</returns>   
    public static string RunScript(List<string> scripts,List<PSParam> pars)   
    {   
        Runspace runspace = RunspaceFactory.CreateRunspace();   

        runspace.Open();   

        Pipeline pipeline = runspace.CreatePipeline();   
        foreach (var scr in scripts)   
        {   
            pipeline.Commands.AddScript(scr);   
        }   

        //注入参数   
        if (pars != null)   
        {   
            foreach (var par in pars)   
            {   
                runspace.SessionStateProxy.SetVariable(par.Key,par.Value);   
            }   
        }   

        //返回结果   
        var results = pipeline.Invoke();   
        runspace.Close();   
        StringBuilder stringBuilder = new StringBuilder();   
        foreach (PSObject obj in results)   
        {   
            stringBuilder.AppendLine(obj.ToString());   
        }   
        return stringBuilder.ToString();   
    }   
}   

/// <summary>   
/// 脚本参数   
/// </summary>   
public class PSParam   
{   
    public string Key   
    {   
        get;   
        set;   
    }   

    public object Value   
    {   
        get;   
        set;   
    }   

}


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

  1. class info   
  2.     {   
  3.         public int x { getset; }   
  4.         public int y { getset; }   
  5.         public int z { getset; }   
  6.     }  
实例化一个对象psobj。。就是上面定义的info
 
给x,y赋值
然后把此对象传给powershell脚本,,参数标识写做arg

static void Main(string[] args)   
{   
    List<string> ps = new List<string>();   
    ps.Add("Set-ExecutionPolicy RemoteSigned");//先执行启动安全策略,,使系统可以执行powershell脚本文件   

    string pspath = System.IO.Path.Combine(Environment.CurrentDirectory,"ps.ps1");   

    ps.Add(pspath);//执行脚本文件   

    info psobj = new info();   
    psobj.x = 20;   
    psobj.y = 10;   

    BaseCommon.PSParam par=new BaseCommon.PSParam();   
    par.Key="arg";   
    par.Value=psobj;   

    BaseCommon.PowerShell.RunScript(ps, new List<BaseCommon.PSParam>() { par });   

    Console.WriteLine(psobj.x + " + " + psobj.y + " = " + psobj.z);   

    Console.ReadLine();   
}


接下来就看写一个简单的powershell脚本来操作.net实例了
 
  1. $a=$arg.x   
  2. $b=$arg.y   
  3. $arg.z=$a+$b  
 
其中$arg就表示上面注入的psobj对象。。标识为arg


原创粉丝点击