Calling PowerShell From C#

后端 未结 2 1867
猫巷女王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:38

    I have done my research and PowerShell.Invoke( IEnumerable ) will set the InputObject of the first command in the list. Therefore instead of setting InputObject on inputCmd above, we can instead pass it through the Invoke method. We still need the first ForEach-Object call to pass the input array to.

    0 讨论(0)
  • 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<PSObject> results = ps.Invoke();
    foreach (PSObject result in results)
    {
        Console.WriteLine(result);
    }
    

    returns:

    2
    4
    6
    
    0 讨论(0)
提交回复
热议问题