Tuesday, June 2, 2009

C#: Running PowerShell from C#

This is a class that allows to execute PowerShell scripts from C#



using System.Management.Automation;
using System.Management.Automation.Runspaces;

/// <summary>
/// PowerShellExecutor
/// </summary>
public class PowerShellExecutor
{
Runspace _runspace = null;
Pipeline _pipeline = null;

/// <summary>
/// .ctor
/// </summary>
public PowerShellExecutor()
{
_runspace = RunspaceFactory.CreateRunspace();
_runspace = RegisterCmdlets(_runspace, _runspace.CreatePipeline());
_pipeline = _runspace.CreatePipeline();
}

public void ClearErrors()
{
_pipeline = _runspace.CreatePipeline("$error.Clear()");
_pipeline.Invoke();
}

/// <summary>
/// ExecuteCmdlet
/// </summary>
/// <param name="command"></param>
/// <param name="rs"></param>
/// <param name="pipe"></param>
/// <returns></returns>
/// <example>
/// PowerShellExecutor p = new PowerShellExecutor();
/// Collection<PSObject> c = p.ExecuteCmdlet("$w = Get-Web 'MySite - 80'", null);
/// c = p.ExecuteCmdlet("[System.Console]::WriteLine($w)", null);
/// </example>
public Collection<PSObject> ExecuteCmdlet(string command)
{
// create pipeline
_pipeline = _runspace.CreatePipeline();

// add script to execute
_pipeline.Commands.AddScript(command);

// execute
Collection<PSObject> results = _pipeline.Invoke();
StringBuilder result = new StringBuilder();

// check results
if (results.Count == 0)
{
result = new StringBuilder();
result.Append("$error");
_pipeline = _runspace.CreatePipeline(result.ToString());
results = _pipeline.Invoke();
}

// return
return results;
}

/// <summary>
/// RegisterCmdlets
/// </summary>
/// <param name="runspace"></param>
/// <param name="pipeline"></param>
/// <returns></returns>
private Runspace RegisterCmdlets(Runspace runspace, Pipeline pipeline)
{
Collection<PSObject> results;
StringBuilder command = new StringBuilder();
runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
command.Append("Set-Alias powershell $env:windir\\System32\\WindowsPowerShell\\v1.0\\powershell.exe");
pipeline = runspace.CreatePipeline(command.ToString());
results = pipeline.Invoke();

command = new StringBuilder();
command.Append("Add-pssnapin Microsoft.SharePoint.PowerShell");
pipeline = runspace.CreatePipeline(command.ToString());
results = pipeline.Invoke();
return runspace;
}
}

No comments: