Creating a PowerShell Cmdlet in C#

Creating a PowerShell Cmdlet in C# is actually a fairly straight forward endeavor. At it’s core you simply create a new class that derives from one of two base classes (Cmdlet or PsCmdlet), add properties to the class to accept your parameters, override one or more methods in the base class to provide your functionality, and decorate the class and properties with a few attributes. In this “How To” article I’m going to create a PowerShell Cmdlet that will add/update my hosts file with host names and IP addresses for each of the ingresses that I have configured in my local Kubernetes cluster running on minikube.

Choosing a Cmdlet Name

In PowerShell Cmdlets are named using a Verb-Noun format. For example Get-ChildItem, or Compress-Archive. Not only is this convention, but PowerShell will yell at you if you don’t follow the convention and use one of the “pre-approved” verbs.

WARNING: The names of some imported commands from the module 'Sample' include unapproved verbs that might make them less discoverable. To find the commands with unapproved verbs, run the Import-Module command again with the Verbose parameter. For a list of approved verbs, type Get-Verb.

If you choose to use a unapproved verb you (and anyone using your module) will be greeted with the big wall of yellow warning text above every time the module is loaded. So what are the approved verbs you can use?

Add, Approve, Assert, Backup, Block, Checkpoint, Clear, Close, Compare, Complete, Compress, Confirm, Connect, Convert, ConvertFrom, ConvertTo, Copy, Debug, Deny, Disable, Disconnect, Dismount, Edit, Enable, Enter, Exit, Expand, Export, Find, Format, Get, Grant, Group, Hide, Import, Initialize, Install, Invoke, Join, Limit, Lock, Measure, Merge, Mount, Move, New, Open, Optimize, Out, Ping, Pop, Protect, Publish, Push, Read, Receive, Redo, Register, Remove, Rename, Repair, Request, Reset, Resize, Resolve, Restart, Restore, Resume, Revoke, Save, Search, Select, Send, Set, Show, Skip, Split, Start, Step, Stop, Submit, Suspend, Switch, Sync, Test, Trace, Unblock, Undo, Uninstall, Unlock, Unprotect, Unpublish, Unregister, Update, Use, Wait, Watch, Write

To make things easier these are all defined in constants in the C# reference library. There are 7 classes with these constants: VerbsCommon, VerbsCommunications, VerbsData, VerbsDiagnostic, VerbsLifecycle, VerbsOther, and VerbsSecurity. Here’s the breakdown by class:

ClassNameVerbs
VerbsCommonAdd, Clear, Close, Copy, Enter, Exit, Find, Format, Get, Hide, Join, Lock, Move, New, Open, Optimize, Pop, Push, Redo, Remove, Rename, Reset, Resize, Search, Select, Set, Show, Skip, Split, Step, Switch, Undo, Unlock, Watch
VerbsCommunicationsConnect, Disconnect, Read, Receive, Send, Write
VerbsDataBackup, Checkpoint, Compare, Compress, Convert, ConvertFrom, ConvertTo, Dismount, Edit, Expand, Export, Group, Import, Initialize, Limit, Merge, Mount, Out, Publish, Restore, Save, Sync, Unpublish, Update
VerbsDiagnosticDebug, Measure, Ping, Repair, Resolve, Test, Trace
VerbsLifecycleApprove, Assert, Complete, Confirm, Deny, Disable, Enable, Install, Invoke, Register, Request, Restart, Resume, Start, Stop, Submit, Suspend, Uninstall, Unregister, Wait
VerbsOtherUse
VerbsSecurityBlock, Grant, Protect, Revoke, Unblock, Unprotect

In the case of my demo project, I’ll be updating the hosts file with the IP addresses of my ingresses in kubernetes, so the “Update” verb seems appropriate here. The noun part of the name is much simpler in that there are really now rules other than it should be a noun. In the case of the demo project I’ve chosen to name it “Update-HostsForIngress”.

Getting Started

Now that we have selected a name for our Cmdlet, let’s get started writing some code! Create a new .Net Framework Class Library project in Visual Studio to contain your Cmdlet. Mine is called DotNetNinja.KubernetesModule and I’m targeting .Net Framework 4.7.2.

Next you’ll need to add a NuGet Package reference to one of the Microsoft.PowerShell.X.ReferenceAssemblies packages depending on which version of PowerShell you want to target. I’ve selected the package Microsoft.PowerShell.5.ReferenceAssemblies because I’m targeting PowerShell 5, but there are packages for PowerShell 3, 4 and 5 available.

Now lets start by adding a class for our Cmdlet named UpdateHostsForIngressCmdlet. (You can name this class anything you want, PowerShell will look at the attributes we’ll be adding shortly to determine the actual Cmdlet name, but it is useful to have the name be easy to tell what Cmdlet it is for, especially when you start building up a library of Cmdlets in one project!). This name follows my personal naming convention for Cmdlet classes which is [Verb][Noun]Cmdlet. Basically take the name of the Cmdlet, remove the hyphen, and append Cmdlet to the end. Here’s the starting boiler-plate code for our Cmdlet class:

    public class UpdateHostsForIngressCmdLet: Cmdlet
    {
        public UpdateHostsForIngressCmdLet()
        {
        }

        public UpdateHostsForIngressCmdLet(IHostsFile hosts, IKubernetesCluster cluster)
        {
        }
        
        protected internal IHostsFile Hosts { get; private set; }

        protected internal  IKubernetesCluster Cluster { get; private set; }
        
        public string[] HostNames { get; set; }

        protected override void BeginProcessing()
        {
        }

        protected override void ProcessRecord()
        {
        }

        protected override void EndProcessing()
        {
        }

        protected override void StopProcessing()
        {
        }
    }

We have a class named UpdateHostsForIngressCmdlet that derives from Cmdlet in System.Management.Automation. (This is the assembly that was added when we added our package reference earlier.) We could also have derived from PsCmdlet, but we don’t need any of the enhanced features of that class (PsCmdlet itself derives from Cmdlet). The biggest use case I have seen for deriving from PsCmdlet is to get access to session storage that allows you to persist info across invocations of your Cmdlet. We won’t need that here, so we’ll just stick with Cmdlet. In order to tell PowerShell that this is a Cmdlet and what it’s name is we need to add a Cmdlet Attribute to the class, specifying two parameters, one for the verb portion of the name and one for the noun portion of the name:

    [Cmdlet(VerbsData.Update, Nouns.HostsForIngress)]
    public class UpdateHostsForIngressCmdLet: Cmdlet
    {
        ...

In the example above I’ve used constants for the names (The built in VerbsData.Update and a custom Nouns.HostsForIngress), but you can just use strings literals if you prefer though I do recommend at least using the built in verbs constants as it prevents you from using an unapproved verb. In addition to the Cmdlet attribute, we should also tell PowerShell about the types we will be outputting from our Cmdlet. We do this by adding an OutputType attribute to the class.

    [Cmdlet(VerbsData.Update, Nouns.HostsForIngress)]
    [OutputType(typeof(HostsUpdateResult))]
    public class UpdateHostsForIngressCmdLet: Cmdlet
    {
        ...

In our class we have two constructors, one default/empty constructor that PowerShell will use to instantiate our class and one that takes the two dependencies we have a parameters. The two dependencies are IHostsfile (which we will use to load and save our hosts file and to manage merging entries for our ingresses) and IKubernetesCluster (which we will use to communicate with our kubernetes cluster to get the information we need about our configured ingresses). Either way the class is constructed/instantiated, we’ll need to make sure the properties Hosts & Cluster get initialized so we can use them later.

    [Cmdlet(VerbsData.Update, Nouns.HostsForIngress)]
    [OutputType(typeof(HostsUpdateResult))]
    public class UpdateHostsForIngressCmdLet: Cmdlet
    {
        public UpdateHostsForIngressCmdLet()
        {
            var services = new ServiceLocator();
            Hosts = services.Get<IHostsFile>();
            Cluster = services.Get<IKubernetesCluster>();
        }

        public UpdateHostsForIngressCmdLet(IHostsFile hosts, IKubernetesCluster cluster)
        {
            Guard.IsNotNull(hosts, nameof(hosts));
            Guard.IsNotNull(cluster, nameof(cluster));
            Hosts = hosts;
            Cluster = cluster;
        }
        ...

In the first constructor I’ve used a ServiceLocator (built on top of Autofac) to instantiate my services. In the second constructor I’ve simply validated the passed in parameters are not null and initialized the service properties with them. This pattern keeps things loosely coupled and should make testing and modification/maintenance easier.

In addition to the two protected properties for our dependencies, we also have a string[] property called HostNames. We’ll use this (optionally if the value is provided) to filter the ingresses we are updating in our hosts file. To tell PowerShell about our parameter property we need to add another attribute, the Parameter Attribute, to the property declaration like so:

        [Parameter(Mandatory = false, Position = 0, ValueFromPipeline = true)]
        public string[] HostNames { get; set; }

Technically all that is required is the attribute itself [Parameter], but I’ve added Mandatory=false so that the parameter isn’t required (if not passed we’ll process all of the ingresses reported by Kubernetes), Position=0 so that our Cmdlet can be invoked with a parameter, but without specifying the name (The first/0th parameter will be mapped to our property), and ValueFromPipeline=true so that we can pipeline in the HostNames if we wish (maybe we’ll want to read them from a file?). With this configuration here are the valid invocations of our command.

# Will update all reported ingresses in the hosts file
Update-HostsForIngress  

# Will update only the specified ingress (kiali.minikube.local) using positional parameter mapping  
Update-HostsForIngress kiali.minikube.local

# Will update only the specified ingress (kiali.minikube.local) using named parameter mapping  
Update-HostsForIngress -HostNames kiali.minikube.local

# Will update all the specified ingresses using positional parameter mapping  
Update-HostsForIngress kiali.minikube.local, dashboard.minikube.local

# Will update all the specified ingresses using named parameter mapping  
Update-HostsForIngress -HostNames kiali.minikube.local, dashboard.minikube.local

# Will update all the specified ingresses using the pipeline as a parameter source  
"kiali.minikube.local", "dashboard.minikube.local" | Update-HostsForIngress

# Alternatively, same as above using a file as the source of the host names
Get-Content .\hostnames.txt | Update-HostsForIngress

Interacting With the PowerShell Session

In order to communicate/output information there are a number of “Write” methods on the Cmdlet base class:

WriteCommandDetailWrites information to the logs.
WriteDebugWrites information out to the debug stream. This is only visible if the -Debug flag is used.
WriteErrorWrites error information.
WriteInformationWrites informational messages out for user consumption.
WriteObjectWrites data objects out to the pipeline stream.
WriteProgressWrites progress information
WriteVerboseWrites writes information to the Verbose stream, This is only visible if -Verbose flag is used.
WriteWarningWrites warning messages for user consumptions. Typically shows as yellow text.

In our Cmdlet we’ll use WriteObject to pass our result objects back to the pipeline. Typically these will just be dumped to the console, but they could be pipelined into another Cmdlet as well. We’ll also use WriteWarning in a couple of cases and we’ll use WriteError in the case that kubectl is not found on the path.

Cmdlet Lifecycle

All that’s left from our initial stubbed out class is the four methods BeginProcessing, ProcessRecord, EndProcessing, StopProcessing. These four methods form the lifecycle of our Cmdlet. Here’s how they work.

BeginProcessing()

This methods is called once per invocation of our Cmdlet. It is intended to be used to initialize things in your Cmdlet like connections, or reading source files etc. We’ll use this method to load our Hosts file.

        protected override void BeginProcessing()
        {
            Hosts.Load();
        }

ProcessRecord()

This method is called once per item being processed. For example if you are pipelining data to your Cmdlet, it will be called once for each item passed by the pipeline. This is typically where you do the bulk of your work in your Cmdlet. In ProcessRecord we will connect to our Kubernetes cluster and get a list of all the currently configured ingresses and upsert the hostnames/IP addresses to our hosts file, merging them with any existing entries.

protected override void ProcessRecord()
        {
            try
            {
                var responses = Cluster.GetIngresses().ToList(); // Get all configured ingresses

                if (responses.Any()) // Only process if kubernetes returns a response
                {
                    // Grab the valid ingress entries for our purposes (only port 80/443 & not the header info)
                    var ingresses = responses.GetValidIngresses().ToList(); 
                    // Filter the ingresses by hostnames if they have been supplied
                    if (HostNames != null && HostNames.Any()) 
                    {
                        ingresses = ingresses.Where(ingress => HostNames.Contains(ingress.Hosts)).ToList();
                    }
                    
                    // Upsert the entries to the hosts file and capture the results for output
                    var results = ingresses.Select(ingress =>
                            Hosts.Upsert(ingress.Address, ingress.Hosts, $" Name: {ingress.Name} Namespace: {ingress.Namespace} EntryDate:{DateTime.Now}"))
                        .OrderBy(result => result.Status)
                        .ThenBy(result => result.HostName);
                    // Output each result as a separate object to allow better pipelining to other Cmdlets
                    foreach (var result in results)
                    {
                        WriteObject(result);
                    }
                    return;
                }
                // Warn the user if Kubernetes did not respond
                WriteWarning("No response was received from kubernetes.  Is your cluster running? (If running minikube locally, try 'minikube status' and/or 'minikube start')");
            }
            catch (Win32Exception ex)
            {
                // Handle the case when kubectl is not installed or is not on the path by showing a warning/error
                if (ex.Message.Contains("The system cannot find the file specified."))
                {
                    WriteWarning("The kubectl command was not found on your system. (Is it installed and on your path?)");
                    WriteError(new ErrorRecord(ex, Errors.KubectlNotFound, ErrorCategory.ResourceUnavailable, Cluster));
                    return;
                }
                // Re-throw any unknown errors
                throw;
            }
        }

EndProcessing()

EndProcessing as you may have guessed is called once processing is completed. This method is also called only once per invocation and is a place to run any clean up code and finalize things before exiting your Cmdlet. We’ll save any pending changes from EndProcessing.

        protected override void EndProcessing()
        {
            Hosts.Save();
        }

StopProcessing()

StopProcessing is called when your Cmdlet terminates prematurely. For example if you start the Cmdlet and then it [ctrl]-[c] then StopProcessing will fire giving you a chance to clean up anything you need to before the Cmdlet exits. We don’t have anything really useful to put in here for our Cmdlet.

Now, in theory, we have a working Cmdlet!

Debugging Your CmdLet

I’ve seen a couple of different ways people have proposed to debug Cmdlets written in C#. Most of them involve a lot of hoop jumping and attaching to processes manually from Visual Studio. By far the best, IMHO, is to configure your project in Visual Studio to debug by launching an external program (powershell.exe) and to pass it a set of command line parameters which among other things automatically loads your module. To do this, in Visual Studio right click on your project and select Properties. In the properties window go to the debug tab and set the following:

Start external program = C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
Command line arguments = -NoProfile -NoExit -Command “Import-Module .\DotNetNinja.KubernetesModule.dll”

Your PowerShell path may vary on your system depending on configuration. Notice that I’m pointed to a v1.0 directory? Apparently v1.0 doesn’t mean what you’d think it means. This is the correct path for my local PowerShell 5 install and as far as I have seen this is a pretty standard path unless you made some explicit choices during system set up.

Now if you click the run button or press f5 a PowerShell window should open and your Cmdlet Module should already be loaded. Just set a break-point and invoke your command to debug.

Importing Your Cmdlet

There are a number of ways you can import your custom Cmdlet. The easiest way is just to import the dll directly from the command prompt. Just type Import-Module and the path to your dll.

Import-Module .\DotNetNinja.KubernetesModule.dll

This works fine if the Cmdlet is just for your own personal consumption and you don’t use it very often.

Another way to make it more easily available is to put it a location on your PowerShell Modules Path. You can see all the locations on your path using:

$env:PSModulePath

Typically there is a user specific path @ ~\Documents\WindowsPowerShell\Modules. Create a folder in the modules folder with the same name as your module and place your dll inside there. Now you can load it without specifying the path and it is discoverable using the Get-Module -ListAvailable command.

Using Module Manifest Files

To make your module available without specifying the dll you can create a Module Manifest file (a .psd1 file). The best way to scaffold out a manifest file is to use the New-ModuleManifest Cmdlet. In our case I’ve created one using:

New-ModuleManifest DotNetNinja.KubernetesModule.psd1

By using this command it will automatically generate a unique guid for your module. If you choose to use another means (like copying an existing file), be sure to generate a new guid for for module! Also be sure to set the RootModule so that PowerShell knows what to load. Here is a stripped down version of the one for my module.

#
# Module manifest for module 'DotNetNinja.Kubernetes'
#
# Generated by: DotNetNinja
#
# Generated on: 2020-02-29
#

@{

RootModule = 'DotNetNinja.KubernetesModule.dll'
ModuleVersion = '1.0.0'
GUID = '9b2f7509-1bac-4ea6-8211-798a920baa2c'
Author = 'Larry House'
Copyright = '(c) Larry House. All rights reserved.'
Description = 'PowerShell Cmdlets for managing Kubernetes environments'
PowerShellVersion = '5.0'
CLRVersion = '4.0'
ProcessorArchitecture = 'Amd64'
FunctionsToExport = '*'
CmdletsToExport = '*'
VariablesToExport = '*'
AliasesToExport = '*'
PrivateData = @{

    PSData = @{


    } # End of PSData hashtable

} # End of PrivateData hashtable

}

Source Code

You can get the full source code from GitHub.

git clone https://github.com/DotNet-Ninja/DotNetNinja.PowerShellModules.git

Resources

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.