快速找出System.Management.Automation.dll,c#调用powershell

 public static void InvokeSystemPS(string cmd)
        {
            List<string> ps = new List<string>();
            ps.Add("Set-ExecutionPolicy RemoteSigned");
            ps.Add("Set-ExecutionPolicy -ExecutionPolicy Unrestricted");
            ps.Add("& " + cmd);
            Runspace runspace = RunspaceFactory.CreateRunspace();
            runspace.Open();
            Pipeline pipeline = runspace.CreatePipeline();
            foreach (var scr in ps)
            {
                pipeline.Commands.AddScript(scr);
            }
            pipeline.Invoke();//Execute the ps script
            runspace.Close();
        }
PowerShell应为编写和运行都很方便,所以为了重复利用,经常写了一些小方法或者PS代码片段。使用的时候可能会很难找到自己想要的那个方法,如果要是有一个界面把这些代码管理起来并且调用,那就很爽了

1.创建一个powershell的方法,供C#调用,方法很简单,两个数的加法运算

function Sum

{

param([int]$first, [int]$second)

 

$result = $first + $second

 

return $result

}

 

 2. 在C#的控制台程序中创建一个私有方法,调用powershell

首先定义一个powershell存放路径的全局变量

private static string script =File.ReadAllText(@"Path\Sum.ps1");

        private static void CallPS1()

        {

            using (Runspace runspace = RunspaceFactory.CreateRunspace())

            {

                runspace.Open();

                PowerShell ps = PowerShell.Create();

                ps.Runspace = runspace;

                ps.AddScript(script);

                ps.Invoke();

 

                ps.AddCommand("Sum").AddParameters(

                    new Dictionary<string, int>()

                    {

                        {"first", 5},

                        {"second", 4}

                    }

                    );

                foreach (PSObject result in ps.Invoke())

                {

                    Console.WriteLine("CallPS1()");

                    Console.WriteLine(result);

                }

            }

        }

调用方法需要添加一个引用System.Management.Automation.dll 
powershell命令行找System.Management.Automation.dll命令 : [psobject].Assembly.Location
posted @ 2017-05-19 15:04  小小高  阅读(3159)  评论(0编辑  收藏  举报