Andre de Cavaignac

Let's blog it out...

Invoking PowerShell Scripts from An Application

If you want to run your PowerShell scripts from a piece of code you're writing, and would prefer not to use Process.Start, you can easily use the PowerShell runtime classes to run those scripts for you, completely in-process.

The code snippit below shows how you can create a Runspace and pass it some simple commands.

List<Command> commands = new List<Command>();
commands.Add(new Command("set-location c:\\"));
commands.Add(new Command("./MyScript.ps1 'myParameter'", true));

using (Runspace runspace = RunspaceFactory.CreateRunspace())
{
    runspace.Open();
    using (Pipeline pipeline = runspace.CreatePipeline())
    {
        foreach (Command cmd in commands)
        {
            pipeline.Commands.Add(cmd);
        }
        pipeline.Invoke();
    }
    runspace.Close();
}

One thing to note here is you do not have a PSHost, so if you have a write-host anywhere, it will fail with the following exception:

CmdletInvocationException: Cannot invoke this function becasue the current host does not implement it.

To get around this, you can remove write-host from your scripts and just have them write single lines, or you can implement a simple PSHost (although this is a bit harder than it sounds).

Leave a Comment

(required) 

(required) 

(optional)

(required)