![]() |
Languages »
C# »
How To
Intermediate
License: The Code Project Open License (CPOL)
How to run PowerShell scripts from C#By Jean-Paul MikkersAn article on embedding and/or launching PowerShell scripts from a C# program. |
C# 2.0.NET 2.0, Vista, .NET 3.0VS2005, Dev
|
|
Advanced Search |
|
|
|
||||||||||||||||

This article contains a bare-bones sample on how to add PowerShell scripting to your C# programs. To paraphrase that movie: "the Power of Shell compels you!"
With the release of Windows PowerShell 1.0 in November 2006, we finally have a powerful command line shell for Windows, one that rivals or even exceeds the capabilities of the common Unix/Linux shells such as csh and bash. The reason for this is that PowerShell commands can read and write objects, as opposed to conventional shells that can only process strings of text. Because PowerShell runs on the .NET platform, the objects that are used are .NET objects, which makes it an ideal scripting language for .NET programs.
Before you can compile the sample code, you'll need a couple of things. First of all, you have to install PowerShell itself, of course, which you can find at the following location: PowerShell homepage. The sample program also references some assemblies that aren't included with the standard PowerShell installation, so you'll have to get those by installing the Windows SDK for Windows Server 2008 and .NET Framework 3.5. Don't worry: even though the latter has 'Server 2008' in its name, it will also install on Vista and XP.
To add PowerShell scripting to your program, you first have to add a reference to the System.Management.Automation assembly. The SDK installs this assembly in the C:\Program Files\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0 directory.
Then, you have to add the following 'using' statements to import the required types:
using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
The following code block shows the RunScript method that does all the hard work. It takes the script text, executes it, and returns the result as a string.
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 = pipeline.Invoke();
// 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();
}
Before executing the script using the pipeline.Invoke() call, it's possible to expose the objects of your program to the script by using the method runspace.SessionStateProxy.SetVariable("someName", someObject). This will create a named variable that the script can access (getting/setting properties, and even calling methods). As an example, suppose we would expose the main form of the sample to the script by adding the SetVariable() call like this:
...
// open it
runspace.Open();
runspace.SessionStateProxy.SetVariable("DemoForm", this);
....
Then, the following script would print the caption of the window:
$DemoForm.Text
The following script would show all the properties and methods of the window:
$DemoForm | Get-Member
Please note, however, that any calls a script makes to your objects will be from another thread context, as pipeline.Invoke() seems to start its own worker thread. This means that your exposed objects will have to be thread-safe.
As an extra feature, I added the ability to drag-n-drop a script on the form, so you don't have to copy-paste PowerShell scripts into the textbox all the time.
| You must Sign In to use this message board. | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
General
News
Question
Answer
Joke
Rant
Admin
|
PermaLink |
Privacy |
Terms of Use
Last Updated: 29 Aug 2008 Editor: Sean Ewington |
Copyright 2007 by Jean-Paul Mikkers Everything else Copyright © CodeProject, 1999-2009 Web13 | Advertise on the Code Project |