Found this interesting article on Code Project the other day, on how to run PowerShell scripts from within C#.
http://www.codeproject.com/KB/cs/HowToRunPowerShell.aspx
Prerequisites:
Code:
Add a reference System.Management.Automation from C:\Program Files\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0
Import
using System.Management.Automation;
using System.Collections.ObjectModel;
using System.Management.Automation.Runspaces;
Note: I did have to edit his function, to get it to work for me, and also added a try/catch to spew out the error.
private string RunScript(string scriptText)
{
// create Powershell runspace
Runspace runspace = RunspaceFactory.CreateRunspace();
// open it
runspace.Open();
// create a pipeline and feed it the script text
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(scriptText);
// add an extra command to transform the script output objects into nicely formatted strings
// remove this line to get the actual objects that the script returns. For example, the script
// "Get-Process" returns a collection of System.Diagnostics.Process instances.
pipeline.Commands.Add("Out-String");
// execute the script
Collection<PSObject> results = new Collection<PSObject>();
try
{
results = pipeline.Invoke();
}
catch (Exception ex)
{
results.Add(new PSObject((object)ex.Message));
}
// close the runspace
runspace.Close();
// convert the script result into a single string
StringBuilder stringBuilder = new StringBuilder();
foreach (PSObject obj in results)
{
stringBuilder.AppendLine(obj.ToString());
}
return stringBuilder.ToString();
}
Technorati Tags:
.Net,
3.0,
C#,
powershell