See How to Call PowerShell Scripts From Your Application

Join James Brundage, Tester from the Windows PowerShell team, and me for a quick introduction to how embed PowerShell within your C# application.

See how you can easily reference the PowerShell assembly and start embedding PowerShell cmdlets inside of a C# application with PowerShell V2.

C# Sample Code

using System.Management.Automation;
using System.Management.Automation.Runspaces;

/* Calls the Get-Process PowerShell command and returns the output as a string */

foreach (string str in PowerShell.Create().
AddScript("Get-Process").
AddCommand("Out-String").Invoke<string>())

{

  Console.WriteLine(str);

}

NOTE: You'll need to add a reference to the version of PowerShell you have installed in your GAC to the Visual Studio project file. To do so, you'll open the project file as a text file and add the following line into the <ItemGroup> section:

<Reference Include="System.Management.Automation" /> 

powershellAbout PowerShell

Windows PowerShell is a new Windows command-line shell designed especially for system administrators. The Windows PowerShell includes an interactive prompt and a scripting environment that can be used independently or in combination.

Unlike most shells, which accept and return text, Windows PowerShell is built on top of the .NET Framework common language runtime (CLR) and the .NET Framework, and accepts and returns .NET Framework objects. This fundamental change in the environment brings entirely new tools and methods to the management and configuration of Windows.

To provide users with a scripting experience, ISVs enable their apps to be called from PowerShell. Developers also use PowerShell to help manage software builds, create virtual machines in Hyper-V, and more.

To go deeper into using PowerShell, see Windows PowerShell SDK on MSDN. The Development Kit is written for command developers who require reference information about the APIs provided by Windows PowerShell. Command developers use Windows PowerShell to create both commands and providers that extend the tasks that can be performed by Windows PowerShell.

PowerShell is included in Windows 7 and Windows Server 2008 R2.

 

Bruce D. KyleISV Architect Evangelist | Microsoft Corporation

cid:image010.png@01C9DEED.1FDB2200 cid:image011.png@01C9DEED.1FDB2200 cid:image012.gif@01C9DEED.1FDB2200 channel9

Special thanks to James Brundage.

Add to Technorati Favorites

Bookmark and Share