§ October 15, 2014 13:40 by
beefarino |
Earlier today I responded to a shout for help from twitter friend and fellow PowerShell hacker Tim Meers:
After sending Tim some code showing how to host simple PowerShell scripts in your application, I’ve received several requests from others for the same. I figured it was worth a quick blog post.
The annotated code is below. This host accepts an item path as input, and uses PowerShell to fetch and format the item as text.
using System;
using System.Linq;
// you'll need to add a reference to System.Management.Automation
using System.Management.Automation;
using System.Management.Automation.Runspaces;
namespace HostSample
{
class Program
{
// to run this application, specify a path to an item
// e.g.:
// c:\
// env:/computername
// hkcu:/software
static void Main(string[] args)
{
// create a RUNSPACE - this is used to maintain state between pipelines.
// e.g., variables, function definitions, etc
using (var runspace = RunspaceFactory.CreateRunspace())
{
// open the runspace before you use it
runspace.Open();
// set the default runspace for the process;
// this is necessary for some features and cmdlets to work properly
Runspace.DefaultRunspace = runspace;
// create a POWERSHELL pipeline
using (var powershell = PowerShell.Create())
{
// assign the runspace to the pipeline
powershell.Runspace = runspace;
// build up the pipeline
powershell.AddCommand("get-item")
.AddParameter("path", args[0])
.AddCommand("format-table")
.AddCommand( "out-string");
// execute the pipeline
var results = powershell.Invoke();
// output the results
Console.WriteLine( results.FirstOrDefault() );
}
}
}
}
}
If you have any questions, please ask them in the comments.
Enjoy!