C# Invoke Powershell with pre-created object

2019-02-26 04:30发布

问题:

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.
        }