2

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 Answer 1

3

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.
        }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.