Custom PowerShell Commands

on Monday, November 23, 2009

To Create Custom Cmdlet, Your class can inherit from either PSCmdlet or Cmdlet class.

You could override below methods.
BeginProcessing-- Provides optional one-time, preprocessing functionality for the cmdlet.
ProcessRecord -- Provides record-by-record processing functionality for the cmdlet. It may be called any number of times or not at all, depending on the input of the cmdlet.

EndProcessing Provides optional one-time, post-processing functionality for the cmdlet.
StopProcessing Stops processing when the user stops the cmdlet asynchronously, such as by entering the key combination Ctrl+C.

To register this cmdlet you need to create a custom SnapIn by inheriting from PSSnapIn or CustomPSSnapin
You have to override below property.
Description: Supply short description of your Snap-in here.

Name: Supply name of your Snap-in here.
Vendor: Supply vendor information for your Snap-in here.
Cmdlets: This is where you provide collection of Cmdlets that need to be registered. I will discuss this in details.

Make sure you override the CmdLets property which should return all the Cmdlets that you want to register with PowerShell.
public override Collection Cmdlets

if (null == _cmdlets)
_cmdlets = new Collection();
_cmdlets.Add(new CmdletConfigurationEntry
("Get-Book", typeof(GetBookCommand), "AmazonPS.dll-Help.xml"));
return _cmdlets;

You need to mark the class with RunInstaller attribute

Then you have to install this snapin using installUtil 64 bit utility.
Then the snapin will be registered with the powershell.

Every time you open the powershell console. You have to run Add-PSSnapIn command.