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:
- Powershell
- Windows SDK for Windows Vista and .Net 3.0 (can also be run on XP SP2).
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();
}
4 comments:
Thanks for the lead ... I was wondering how I was going to hide some Exchange Management Shell scripts behind a C# webservice, and this seems like a start.
- Albany NY
Very cool! You might want to use the brand new Windows SDK, just released today. The RTM release of the Microsoft Windows SDK for Windows Server 2008 and .NET Framework 3.5 is now live on the Microsoft Download Center. Web install: http://www.microsoft.com/downloads/details.aspx?FamilyId=E6E1C3DF-A74F-4207-8586-711EBE331CDC&displaylang=en
ISO install: http://www.microsoft.com/downloads/details.aspx?FamilyId=F26B1AA4-741A-433A-9BE5-FA919850BDBF&displaylang=en
Karin Meier
Windows SDK Team
Awesome, thanks for the information on the update.
How can I piped the where clause command? For eg. if i need to code this in C#, what woould it be?
Get-CPUType -VMMServer $vmmServer | where {$_.Name -eq "$cpu"}
Post a Comment