Monday, November 21, 2011

Running PowerShell script from C#

To run the PowerShell scripts from C# add a reference to System.Management.Automation assembly and include the following namespaces

using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Management.Automation.Runspaces;

private string RunScript(string scriptText)
{
    Runspace runspace = RunspaceFactory.CreateRunspace();
    runspace.Open();
    Pipeline pipeline = runspace.CreatePipeline();
    pipeline.Commands.AddScript(scriptText);
    pipeline.Commands.Add("Out-String");
    Collection results = pipeline.Invoke();
    runspace.Close();
    StringBuilder stringBuilder = new StringBuilder();
    foreach (PSObject obj in results)
    {
        stringBuilder.AppendLine(obj.ToString());
    }
    return stringBuilder.ToString();
}

No comments:

Post a Comment