Click here to Skip to main content
11,430,708 members (72,347 online)
Click here to Skip to main content

How to run PowerShell scripts from C#

, 29 Aug 2008 CPOL
Rate this:
Please Sign up or sign in to vote.
An article on embedding and/or launching PowerShell scripts from a C# program.

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)

Share

About the Author

jpmik
Architect
Netherlands Netherlands
No Biography provided

Comments and Discussions

 
QuestionCredential error with a complex script Pin
aSnoussi1-May-13 2:33
memberaSnoussi1-May-13 2:33 
QuestionHow to execute Hyper-V Powershell Cmdlets command (GET-VM) in Windows Server 2012 using VS2010 C#?? Pin
Alok Kumar Sharma1-Apr-13 12:45
memberAlok Kumar Sharma1-Apr-13 12:45 
AnswerRe: How to execute Hyper-V Powershell Cmdlets command (GET-VM) in Windows Server 2012 using VS2010 C#?? Pin
jpmik2-Apr-13 11:39
memberjpmik2-Apr-13 11:39 
AnswerRe: How to execute Hyper-V Powershell Cmdlets command (GET-VM) in Windows Server 2012 using VS2010 C#?? Pin
roninttk24-Mar-14 8:24
memberroninttk24-Mar-14 8:24 
QuestionApplication hangs if I run .cmd script Pin
Member 167164322-Feb-13 19:03
memberMember 167164322-Feb-13 19:03 
QuestionPowerShell scripts from C# Failed while runing "Get-Content -Wait C:\TEMP\producer.txt" Pin
Yuri Shterenberg3-Feb-13 0:23
memberYuri Shterenberg3-Feb-13 0:23 
GeneralSimple typos or fix in code [modified] Pin
rama charan28-Jan-13 20:02
memberrama charan28-Jan-13 20:02 
Questionhow to add ad user from sql table Pin
ocean_blue421-Sep-12 1:18
memberocean_blue421-Sep-12 1:18 
QuestionXML Exporting Pin
vipfangirl11-Sep-12 23:57
membervipfangirl11-Sep-12 23:57 
QuestionScheduled ShutdownVMGuest_Task Pin
trobolan21-Aug-12 3:21
membertrobolan21-Aug-12 3:21 
AnswerRe: Scheduled ShutdownVMGuest_Task Pin
jpmik23-Aug-12 6:41
memberjpmik23-Aug-12 6:41 
GeneralRe: Scheduled ShutdownVMGuest_Task Pin
trobolan23-Aug-12 21:18
membertrobolan23-Aug-12 21:18 
GeneralMy vote of 4 Pin
Burak Tunçbilek29-Jul-12 12:59
memberBurak Tunçbilek29-Jul-12 12:59 
thank you
Questionimprovements Pin
kiquenet.com25-May-12 0:33
memberkiquenet.com25-May-12 0:33 
QuestionCan not run backup script Pin
augustwind21-Apr-12 6:50
memberaugustwind21-Apr-12 6:50 
AnswerRe: Can not run backup script Pin
jpmik21-Apr-12 9:00
memberjpmik21-Apr-12 9:00 
GeneralRe: Can not run backup script [modified] Pin
augustwind21-Apr-12 13:44
memberaugustwind21-Apr-12 13:44 
AnswerRe: Can not run backup script Pin
Bh@nu4-Jul-12 21:52
memberBh@nu4-Jul-12 21:52 
GeneralMy vote of 5 Pin
Rayler21-Mar-12 1:51
memberRayler21-Mar-12 1:51 
QuestionCannot process command because of one or more missing mandatory parameters: ComputerName. Pin
JeremyProg122-Nov-11 11:22
memberJeremyProg122-Nov-11 11:22 
Questionremotely access the server Pin
Absials16-Nov-11 20:59
memberAbsials16-Nov-11 20:59 
QuestionStart Service as an Administrator Pin
Gustavo Eduardo Mendoza Ramirez1-Sep-11 10:38
memberGustavo Eduardo Mendoza Ramirez1-Sep-11 10:38 
GeneralHere's posting that extends this example a bit... Pin
rlrcstr23-Aug-10 4:32
memberrlrcstr23-Aug-10 4:32 
GeneralMy vote of 5 Pin
Scott Munro12-Aug-10 22:30
memberScott Munro12-Aug-10 22:30 
GeneralThe article is great, but I need some help [modified] Pin
Kevin Stock (Atempo)5-Mar-10 4:31
memberKevin Stock (Atempo)5-Mar-10 4:31 
GeneralRe: The article is great, but I need some help Pin
jpmik5-Mar-10 6:21
memberjpmik5-Mar-10 6:21 
GeneralRe: The article is great, but I need some help Pin
Kevin Stock (Atempo)7-Mar-10 21:38
memberKevin Stock (Atempo)7-Mar-10 21:38 
GeneralCool Pin
chunhatbuon198422-Dec-09 8:25
memberchunhatbuon198422-Dec-09 8:25 
GeneralNot working Pin
OlegGelezcov6-Sep-09 1:13
memberOlegGelezcov6-Sep-09 1:13 
GeneralRe: Not working Pin
Jean-Paul Mikkers18-Nov-09 9:54
memberJean-Paul Mikkers18-Nov-09 9:54 
GeneralRe: Not working Pin
Member 769978628-Feb-11 9:56
memberMember 769978628-Feb-11 9:56 
GeneralRe: Not working Pin
shaanr18-Jul-12 4:51
membershaanr18-Jul-12 4:51 
GeneralCode not working Pin
deepak_int26-Mar-09 19:25
memberdeepak_int26-Mar-09 19:25 
GeneralRe: Code not working Pin
deepak_int31-Mar-09 21:03
memberdeepak_int31-Mar-09 21:03 
QuestionHow to run more complex scripts Pin
Kressilac30-Jan-09 10:46
memberKressilac30-Jan-09 10:46 
QuestionRe: How to run more complex scripts Pin
Member 83770974-Nov-11 19:20
memberMember 83770974-Nov-11 19:20 
AnswerRe: How to run more complex scripts Pin
jpmik6-Nov-11 0:28
memberjpmik6-Nov-11 0:28 
GeneralRemote execute poweshell script Pin
Sam S.25-Mar-08 3:54
memberSam S.25-Mar-08 3:54 
GeneralRe: Remote execute poweshell script Pin
Julia10055-Dec-08 6:21
memberJulia10055-Dec-08 6:21 
GeneralRe: Remote execute poweshell script Pin
Barron Gillon5-Jan-09 10:26
memberBarron Gillon5-Jan-09 10:26 
GeneralRe: Remote execute poweshell script Pin
Arrow0fDarkness24-Dec-09 18:20
memberArrow0fDarkness24-Dec-09 18:20 
GeneralRe: Remote execute poweshell script Pin
Absials16-Nov-11 21:02
memberAbsials16-Nov-11 21:02 
GeneralRe: Remote execute poweshell script Pin
kiquenet.com25-May-12 0:27
memberkiquenet.com25-May-12 0:27 
QuestionHow to pass parameters into the Scripts? Pin
igormoochnick8-Feb-08 16:26
memberigormoochnick8-Feb-08 16:26 
QuestionPublishing Methods Pin
cbruun2-Aug-07 0:17
membercbruun2-Aug-07 0:17 
AnswerRe: Publishing Methods Pin
Jean-Paul Mikkers2-Aug-07 5:21
memberJean-Paul Mikkers2-Aug-07 5:21 
GeneralRe: Publishing Methods Pin
cbruun2-Aug-07 12:17
membercbruun2-Aug-07 12:17 
GeneralRe: Publishing Methods Pin
Jean-Paul Mikkers5-Aug-07 3:50
memberJean-Paul Mikkers5-Aug-07 3:50 
GeneralWhere to find the SDK Pin
S. Owens3-Apr-07 10:53
memberS. Owens3-Apr-07 10:53 

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.

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