C#: PowerShellAdappter

Problem

I want to use my PowerShell modules in C# so I can make a ASP.Net webinterface using my PowerShell backend.

Solution

Combining the forces of multiple contributors on the interwebs I created this PowerShellAdapter class.

The addapter creates a Runspace that has ExecutionPolicy disabled and the required modules loaded.
Using the InvokePSCommand(“MyCommand”) function you can retrieve a Collection of PSObjects returned by executing the command.
Any errors will be detected and thrown.

public class PowerShellAdapter
{
    private InitialSessionState iss;

    public PowerShellAdapter()
    {
        iss = InitialSessionState.CreateDefault();
        // Remove ExecutionPolicy
        iss.AuthorizationManager = new System.Management.Automation.AuthorizationManager("none");
        // Importing required modules
        iss.ImportPSModule(new[] { @"MyModule", @"MyOtherModule" });
    }

    public Collection InvokePSCommand(string strScript)
    {
        Runspace objRunspace = RunspaceFactory.CreateRunspace(iss);
        objRunspace.Open();

        Pipeline objPipe = objRunspace.CreatePipeline();

        objPipe.Commands.AddScript(strScript);

        Collection output = null;
        output = objPipe.Invoke();

        objRunspace.Close();

        // Check for errors in the pipeline and throw an exception if necessary
        if (objPipe.Error != null && objPipe.Error.Count > 0)
        {
            StringBuilder pipelineError = new StringBuilder();
            pipelineError.AppendFormat("Error calling Cmdlet.  ");
            foreach (object item in objPipe.Error.ReadToEnd())
            {
                pipelineError.AppendFormat("{0}\n", item.ToString());
            }
            throw new Exception(pipelineError.ToString());
        }
        return output;
    }
}

To use this PowerShellAdapter you can initate it, call the InvokePSCommand function and use the collection however you want.
Here is an example.

public class MyObjectController
{
    private PowerShellAdapter psa;

    public MyObjectController()
    {
        psa = new PowerShellAdapter();
    }
    public List<String> All()
    {
        List<String> list = new List<SPijler>();

        foreach (PSObject psObject in psa.InvokePSCommand("Get-MyObject -All"))
        {
            // You can read any specific attribute from the returned PSObject
            string strOne = (String)psObject.Members["Name"].Value;
            list.Add(strOne);
        }
        return list;
    }
}
Advertisements

Tags: , , , , , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: