C# Invoke Powershell with pre-created object

安稳与你 提交于 2019-12-02 05:34:36

问题


I've just started out with PS and are writing some C# classes which I need to test from within PS.

Please note that these classes are NOT CmdLets.

I want to do something like this:

var myCustomObj = new CustomObj { Message = "Hello world" };

var ps = Powershell.Create();

ps.AddCommand("Import-Module").AddParameter("Assembly", "MyCustomAsm");
ps.AddCommand("myCustomObj.Run()").AddParameter(myCustomObj);

foreach(string str in ps.AddCommand("Out-String").Invoke<string>()) 
        Console.WriteLine(str); 

Where I invoke Run() on the object handed to PS, the result would be a printout "Hello world".

But i'm not even sure that this is possible (might be for security reasons).

I figure I've got 2 options:

  1. Either this is possible. If so please help me :) ?

  2. I will have to generate the script file based on my existing object and the do an "AddScript(...)" to have ps execute it.

Any pointers to get me started would be nice :).

Kind regards.


回答1:


I found a solution:

        var objs= new PSDataCollection<CustomObj> {obj};

        using (var ps = PowerShell.Create())
        {
            ps.Runspace.SessionStateProxy.SetVariable("objList", objs);
            ps.AddScript(@"$objList| ForEach { $_.Run()}");
            ps.AddCommand("Out-String");
            var output = ps.Invoke();

            var stringBuilder = new StringBuilder();
            foreach (var obj in output)
            {
                stringBuilder.AppendLine(obj.ToString());
            }

            var result = stringBuilder.ToString().Trim();

            //Evaluate result.
        }


来源:https://stackoverflow.com/questions/8020635/c-sharp-invoke-powershell-with-pre-created-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!