Basics of the PSCmdlet Class
The PSCmdlet Class, crafting PowerShell commands in C#
The PSCmdlet base class that we inherit from grants us a lot of familiar functionality to craft cmdlets, but this time in C#!
You can find full documentation of the PSCmdlet class here but I wanted to call out a few common methods we will use again and again
Cmdlet Class
First we need a class for our Cmdlet, lets go ahead and inherit from the PSCmdlet base class to get access to all the base libraries goodies! think of this like how we decorate a function to make it a PS Advanced Function
[Cmdlet(VerbsCommon.Get, "Greeting")]
public sealed GetGreetingCmdlet : PSCmdlet
if your IDE does not take care of the dependency here and throws red at you, make sure at the top of the file you add the following using statement
using System.Management.Automation;
We have also decorated this class with the [Cmdlet] decorator/attribute giving it a Cmdlet name
the class is public, as we intend to expose it, but sealed as we don’t want it to be changed
Parameters
The [Parameter] decorator is used to define parameter attributes and should be immediately familiar to you as a PowerShell developer.
Below is a non mandatory parameter called Name of type ‘string’ with a default value
[Parameter(Mandatory = false)]
public string Name { get; set; } = "World!";
ProcessRecord
The ProcessRecord method is akin to the process block in a Poweshell function, and often encapsulates the heavy lifting of the cmdlet
the method exists in a basic form and thus needs to be overridden with our own logic, if we did not have a ProcessRecord method in our class, the default behavior would be observed
protected override void ProcessRecord()
{
WriteObject($"Hello, {Name}!");
}}
Now if everything went to plan you should have a file that looks like this
using System.Management.Automation;
namespace ASNS.Intro;
[Cmdlet(VerbsCommon.Get, "Greeting")]
public sealed class Class1 : PSCmdlet
{
[Parameter(Mandatory = false)]
public string Name { get; set; } = "World!";
protected override void ProcessRecord()
{
WriteObject($"Hello, {Name}!");
}
}
Go ahead and run dotnet build again
if that works you should have a .dll file in ./obj/Debug/net8.0 that we can import straight into powershell
Import-Module <path to dll>
You should now have access to the Get-Greeting cmdlet
Get-Greeting
Get-Greeting -Name <name>
-> Next