This is one of those tasks I need to repeat every now and then and always forget the exact steps. So in the interest of sharing, I’ve written this post to demonstrate how to get started building a very simple module and cmdlet with C# and Visual Studio.

 

A SCREENCAST IS AVAILABLE

If you’d rather watch, this screencast will show you the steps I followed

image

http://vimeo.com/10007373

 

STEP-BY-STEP INSTRUCTIONS

Create a new Visual Studio Class Library Project project.

image

image

In this case, I named the library “DemoPS”.

Now, we will add two references. The first to System.Management and the second to System.Management.Automation

image

System.Management is found under the .NET tab

image

System.Management.Automation is found under c:\program files\reference assemblies\microsoft\WindowsPowershell\v1.0

image

image 

image

And now the references are available in Solution Explorer

image 

 

If you are using Visual Studio 2010 the assembly will be built using .NET 4.0, but you’ll need to switch it to use the older framework so that Powershell can load the assembly.

Edit the properties of the DemoPS project and set the Target Framework to “.NET Framework 3.5”

image

image

 

Now let’s the examine the code …

image

 

Build the cmdlet and launch Powershell 2.0

Import the module with Import-Module

image

The Get-Modules cmdlet will show you that the module is loaded and it has a single cmdlet inside it called “Get-DemoNames”

image

the “-?” parameter is already provided for the cmdlet

image

Now try the cmdlet …

image

And, of course, it behaves just like any other cmdlet. So you can do things like pipe its output …

image