zoukankan      html  css  js  c++  java
  • 快速找出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(@"PathSum.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
  • 相关阅读:
    Adjacent Bit Counts(uvalive)
    UVALIVE 4556 The Next Permutation
    vector(实现存图)
    最大连续子序列和(模板)
    全选和反选
    .netCore上传图片,要用FormFileCollection ,不能用List
    .NET-Core中 HttpContext.Response.Write() 中文输出乱码
    Core中Cookie和Session的新用法
    Ajax反填
    复选框变成单选
  • 原文地址:https://www.cnblogs.com/gaocong/p/6878470.html
Copyright © 2011-2022 走看看