Sample Powershell Cmdlet in C#

Another one from the department of aide memoire. Here’s the basic process to follow when creating a simple PowerShell Cmdlet in C#.

  • Create a new class library.
  • Add a reference to the Microsoft Windows PowerShell Engine core assembly - System.Management.Automation.dll
  • Add a class derived from System.Management.Automation.Cmdlet
  • Add a Cmdlet attribute to the class with a suitable Verb and Noun.
  • Override the ProcessRecord method.
  • Add properties decorated with Parameter attributes.
  • Consider support for WhatIf? and Confirm Impact.
  • Consider applying the OutputType attribute to the class.
  • Use WriteError in catch handlers.
  • Use WriteObject to send results to the pipeline.
  • Create a new Module Manifest (.psd1) using the Powershell New-ModuleManifest cmdlet.
  • Make sure the RootModule setting in the manifest points to the cmdlet dll.
  • Create a folder named the same as the dll in a Module folder somewhere in the PowerShell search path.
  • Copy the .dll and .psd1 (and any other dependencies) into this folder.
  • Open a new PowerShell session and use Import-Module to import the new cmdlet(s).
  • Use the module.
  • Profit!