Click here to Skip to main content
15,118,573 members
Articles / Programming Languages / C#
Posted 31 Mar 2007


160 bookmarked

How to run PowerShell scripts from C#

Rate me:
Please Sign up or sign in to vote.
4.82/5 (59 votes)
29 Aug 2008CPOL3 min read
An article on embedding and/or launching PowerShell scripts from a C# program.

Screenshot - HowToRunPowerShell_Screen.png


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.

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


    // create a pipeline and feed it the script text

    Pipeline pipeline = runspace.CreatePipeline();

    // 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.


    // execute the script

    Collection<psobject /> results = pipeline.Invoke();

    // close the runspace


    // convert the script result into a single string

    StringBuilder stringBuilder = new StringBuilder();
    foreach (PSObject obj in results)

    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.SessionStateProxy.SetVariable("DemoForm", this);

Then, the following script would print the caption of the window:


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


  • 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


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


About the Author

Netherlands Netherlands
No Biography provided

Comments and Discussions

Questionissue with code Pin
Member 1124187320-Sep-20 22:17
MemberMember 1124187320-Sep-20 22:17 
QuestionCalling Powershell script from C# Pin
Member 1483996323-May-20 6:35
MemberMember 1483996323-May-20 6:35 
AnswerRe: Calling Powershell script from C# Pin
bismark5-Apr-21 14:08
Memberbismark5-Apr-21 14:08 
QuestionIam trying to execute the below code. Unable to connect with PowerCli server. Need Help Pin
khan_aamir472-Mar-20 0:45
Memberkhan_aamir472-Mar-20 0:45 
QuestionUse IDisposable Pin
aodennison10-Jul-19 9:53
Memberaodennison10-Jul-19 9:53 
QuestionTypo: An extra / slipped in. Pin
aodennison10-Jul-19 7:36
Memberaodennison10-Jul-19 7:36 
QuestionLink for PowerShell not working Pin
Ammar Shaukat24-Jan-19 0:21
professionalAmmar Shaukat24-Jan-19 0:21 
GeneralMy vote of 5 Pin
Ravi Shankar K18-Aug-16 5:24
MemberRavi Shankar K18-Aug-16 5:24 
QuestionError use Import-Module, please help Pin
shaderz5-Jun-15 3:57
Membershaderz5-Jun-15 3:57 
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 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 
Questionimprovements Pin
kiquenet.com25-May-12 0:33
professionalkiquenet.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 

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

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