@RSS description Create your own Cmdlet base class

Does this site look plain?

This site uses advanced css techniques

When creating a PowerShell cmdlet in C#, your class (Get_ALife) generally derives from the SDK-provided Cmdlet or PSCmdlet classes, but I recommend creating your own intermediate class to derive from, giving you a common place to create cmdlet-wide helpers.

Most cmdlet systems don't need this—which means that the class will be mostly empty—but I've found it a good practice that means I don't have to retrofit a suite of cmdlets when the need comes up (and the need almost always comes up).

// MyCmdlet.cs
using System.Management.Automation;

namespace MyProject {

    public abstract class MyCmdlet : Cmdlet {
        // nothing yet
    }
}

and then in your own individual Cmdlets:

// Get-ALife.cs
using System.Management.Automation;

namespace MyProject {

    [Cmdlet(VerbsCommon.Get, "ALife")]
    public class Get_ALife : MyCmdlet {

          // do stuff

    }
}

Future blog posts will discuss several of the ways I've used this to aid in cooperative processing across a suite of cmdlets, such as common error processing or maintaining state variables across a session.

Another reason to do this: if you've initially built your suite of cmdlets from the base Cmdlet class, which is a more lightweight interface than PSCmdlet, your intermediary class makes it easy to change from one to the other in one place without having to edit every cmdlet's source code.

I've never once removed my own base class from a project even though it wasn't actually doing anything, but I've had to retrofit projects several times when I skipped this step during new-project setup.


First published: 2019/07/05