Click here to Skip to main content
Licence CPOL
First Posted 31 Mar 2007
Views 155,608
Downloads 2,245
Bookmarked 98 times

How to run PowerShell scripts from C#

By jpmik | 29 Aug 2008
An article on embedding and/or launching PowerShell scripts from a C# program.
  4.71 (25 votes)
1 vote, 4.0%
1

2
1 vote, 4.0%
3
6 votes, 24.0%
4
17 votes, 68.0%
5
4.71/5 - 25 votes
1 removed
μ 4.61, σa 1.63 [?]

Screenshot - HowToRunPowerShell_Screen.png

Introduction

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!"

Background

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.

Prerequisites

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.

Using the Code

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();
}

How to Let the Script Interact with your Program

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.

Points of Interest

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.

More Information on PowerShell

History

  • Apr 01, 2007: First release
  • Apr 04, 2007: Minor update
  • Aug 28, 2008: Fixed the broken link to the SDK, and the broken link to my second powershell article

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

jpmik

Architect

Netherlands Netherlands

Member


Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
QuestionCannot process command because of one or more missing mandatory parameters: ComputerName. PinmemberJeremyProg111:22 22 Nov '11  
Questionremotely access the server PinmemberAbsials20:59 16 Nov '11  
QuestionStart Service as an Administrator PinmemberGustavo Eduardo Mendoza Ramirez10:38 1 Sep '11  
GeneralHere's posting that extends this example a bit... Pinmemberrlrcstr4:32 23 Aug '10  
GeneralMy vote of 5 PinmemberScott Munro22:30 12 Aug '10  
GeneralThe article is great, but I need some help [modified] PinmemberKevin Stock (Atempo)4:31 5 Mar '10  
GeneralRe: The article is great, but I need some help Pinmemberjpmik6:21 5 Mar '10  
GeneralRe: The article is great, but I need some help PinmemberKevin Stock (Atempo)21:38 7 Mar '10  
GeneralCool Pinmemberchunhatbuon19848:25 22 Dec '09  
GeneralNot working PinmemberOlegGelezcov1:13 6 Sep '09  
GeneralRe: Not working PinmemberJean-Paul Mikkers9:54 18 Nov '09  
GeneralRe: Not working PinmemberMember 76997869:56 28 Feb '11  
GeneralCode not working Pinmemberdeepak_int19:25 26 Mar '09  
GeneralRe: Code not working Pinmemberdeepak_int21:03 31 Mar '09  
QuestionHow to run more complex scripts PinmemberKressilac10:46 30 Jan '09  
QuestionRe: How to run more complex scripts PinmemberMember 837709719:20 4 Nov '11  
AnswerRe: How to run more complex scripts Pinmemberjpmik0:28 6 Nov '11  
GeneralRemote execute poweshell script PinmemberSam S.3:54 25 Mar '08  
GeneralRe: Remote execute poweshell script PinmemberJulia10056:21 5 Dec '08  
GeneralRe: Remote execute poweshell script PinmemberBarron Gillon10:26 5 Jan '09  
GeneralRe: Remote execute poweshell script PinmemberArrow0fDarkness18:20 24 Dec '09  
GeneralRe: Remote execute poweshell script PinmemberAbsials21:02 16 Nov '11  
QuestionHow to pass parameters into the Scripts? Pinmemberigormoochnick16:26 8 Feb '08  
QuestionPublishing Methods Pinmembercbruun0:17 2 Aug '07  
AnswerRe: Publishing Methods PinmemberJean-Paul Mikkers5:21 2 Aug '07  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web03 | 2.5.120130.1 | Last Updated 29 Aug 2008
Article Copyright 2007 by jpmik
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid