文章出處

 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

文章列表




Avast logo

Avast 防毒軟體已檢查此封電子郵件的病毒。
www.avast.com


arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()