Calling PowerShell From C#

后端 未结 2 1872
猫巷女王i
猫巷女王i 2020-12-06 07:20

I am using System.Management.Automation DLL which allows me to call PowerShell within my C# application like so:

PowerShell.Create().AddScript(\         


        
2条回答
  •  粉色の甜心
    2020-12-06 07:46

    A little bit late but:

    PowerShell ps = PowerShell.Create();
    ps.Runspace.SessionStateProxy.SetVariable("a", new int[] { 1, 2, 3 });
    ps.AddScript("$a");
    ps.AddCommand("foreach-object");
    ps.AddParameter("process", ScriptBlock.Create("$_ * 2"));
    Collection results = ps.Invoke();
    foreach (PSObject result in results)
    {
        Console.WriteLine(result);
    }
    

    returns:

    2
    4
    6
    

提交回复
热议问题