文章出處
文章列表
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
文章列表
全站熱搜