Christian Mikkelsen
Christian Mikkelsen

Reputation: 1701

Save C# Powershell as script file

Im currently using C# to pass some objects to powershell and executing a method on them like this:

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

Question:

Is there a simply way to save my ps object as an script file without doing a lot of writeline? I was thinking something in the lines of:

    ps.SaveAsScript(filename);

This would be a great help in a lot of my work with automation, if this is possible in a simple way.:)

Kind regards

Upvotes: 2

Views: 433

Answers (1)

manojlds
manojlds

Reputation: 301357

No there is not. You will have to get the commands ( ps.Commands.Commands) and write to a file as needed.

Upvotes: 3

Related Questions