Friday, 30 January 2009

Execute Powershell programmatically in C#

Last week I was working on a piece of functionality where I wanted to execute powershell script programmatically. Here is the piece of code for this.

Namespaces to include:

using System.Management.Automation.Runspaces;

using System.Management.Automation;

using System.Collections.ObjectModel;

using System.Collections;

using System.Collections.Generic

This function takes following arguments

· ps1Filename – Poweshell script to excute (full file path)

· WebsiteRootPath, WebsiteURL, ServerEnvironment – these are custom arguments for my powershell (you can replace this with what arguments your ps1 is expecting)

Function:

private string ExecutePowershell( string ps1Filename, string WebsiteRootPath,string WebsiteURL,

string ServerEnvironment)

{

Runspace runspace = RunspaceFactory.CreateRunspace();

runspace.Open();

Pipeline pipeline = runspace.CreatePipeline();

//create command with script path

Command c = new Command(ps1Filename, false);

c.Parameters.Add(new CommandParameter("destinationFolder", WebsiteRootPath));

c.Parameters.Add(new CommandParameter("baseUrl", WebsiteURL));

c.Parameters.Add(new CommandParameter("env", ServerEnvironment));

pipeline.Commands.Add(c);

//create a collection to hold output of script

Collection<PSObject> results = new Collection<PSObject>();

try

{

// execute the script

results = pipeline.Invoke();

}

catch (Exception ex)

{

results.Add(new PSObject((object)ex.Message));

}

runspace.Close();

StringBuilder stringBuilder = new StringBuilder();

//loopthru all the objects returned (each object will contain output text)

foreach (PSObject obj in results)

{

stringBuilder.AppendLine(obj.ToString());

}

return stringBuilder.ToString();

}