快速找出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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值