Powershell

How to write a Cmdlet in PowerShell Step-by-Step

How to write a Cmdlet in PowerShell Step-by-Step. Learn how to write your own cmdlet using Visual Studio and .NET C# code.

Highlights

  • You may be wondering, can’t I just write a function in PowerShell and that is the same as a cmdlet.
  • NET language such as C#It is contained in a dynamic link library (DLL)Functions are written in the PowerShell language from existing PowerShell cmdletsCmdlets are often easier to package and distribute.
  • This post will cover how to write a cmdlet in PowerShell and see what steps are involved in the process.

PowerShell is well, very powerful! If you have worked with PowerShell for any period of time, you have no doubt fallen in love with the cmdlet. The PowerShell cmdlet provides very human readable syntax that allows writing extremely powerful scripts in little time without many lines of code. Have you ever wondered how to write a PowerShell cmdlet? What is the difference between a PowerShell cmdlet and a PowerShell function? This post will cover how to write a cmdlet in PowerShell and see what steps are involved in the process.

PowerShell Cmdlet vs PowerShell Function

You may be wondering, can’t I just write a function in PowerShell and that is the same as a cmdlet? No. These constructs are different. How so? Cmdlets are different than PowerShell functions in the following ways:

  • Cmdlets are written in a complied .NET language such as C#
  • It is contained in a dynamic link library (DLL)
  • Functions are written in the PowerShell language from existing PowerShell cmdlets
  • Cmdlets are often easier to package and distribute

So basically, a cmdlet is written in low-level .NET code. So it is not constructed with other PowerShell cmdlets. PowerShell cmdlets are the verbs that are used when writing the PowerShell verb noun statements. For most of us, the included PowerShell cmdlets that we have access to from various modules found on the PowerShell Gallery. However, what if you have need to write your own PowerShell cmdlet for custom functionality?

How to write a Cmdlet in PowerShell

Writing your own cmdlet in PowerShell is not necessarily a trivial endeavor. You definitely need to know a bit about what you are doing with a .NET language like C#. I am not a programmer and that has never been my strong suit. I can hack my way through example code and change things as needed, so I just wanted to say this to level set here. However, there are plenty of great examples out there and other blog posts that walk through the process for specific cmdlet examples. Microsoft has a very simple cmdlet example that basically outputs a hello to your screen. However, they don’t really show the steps involved to build the code, compile a .DLL file and make it to the point of importing the cmdlet.

You can find this very basic cmdlet example code in the following link.

Windows Powershell vs. PowerShell Core

In the walkthrough of using the sample code provided by Microsoft, we are going to use .NET core and PowerShell Core. PowerShell Core is a new way forward for PowerShell. It is a cross-platform solution that can run on Windows, Mac, and Linux. All the new features and functionality with PowerShell will be introduced into PowerShell Core.

Keep this in mind when creating your new cmdlets as you want to keep the differences of each PowerShell version before creating your cmdlet and which .NET version you want to target.

What we can do is use the example code and step through the process to create the required .DLL file in Visual Studio. I will be using Visual Studio 2017, however, this can be done in other versions as well. Visual Studio 2017 and higher allows easily interacting with .NET core to create your cmdlet.

Using Visual Studio to build the PowerShell Cmdlet .DLL

In Visual Studio 2017, here I am selecting to create a new Project.

Create a new project in visual studio
Create a new project in visual studio

Choose .NET Core > Class Library (.NET Core)

Create a new class library for .net core
Create a new class library for .net core

Under the Solution Explorer, expand your project and right-click Dependencies. Select Manage NuGet Packages.

Manage nuget packages for new powershell cmdlet
Manage nuget packages for new powershell cmdlet

Under the Browse tab type in System.Management.Automation. Download and install the system.management.automation module. The most recent version will display to the right. Here, the latest is v.7.1.1.

Download system.management.automation
Download system.management.automation 1

Once you install the system.management.automation, click the settings for the module (little settings cog) to the right under NuGet Package Manager. Under NuGet Package Manager > Package Sources add a new package source. Name it and use the URL below for the Source.

Add an available package source for creating powershell cmdlet
Add an available package source for creating powershell cmdlet

Accept the notice of changes made to the solution. Click OK.

Accept changes made in visual studio
Accept changes made in visual studio

View and accept the license agreement.

Accept the eula for the downloaded software
Accept the eula for the downloaded software

Now, paste the sample code into the Class1.cs file in Visual Studio.

using System.Management.Automation;  // Windows PowerShell assembly.

namespace SendGreeting
{
  // Declare the class as a cmdlet and specify the
  // appropriate verb and noun for the cmdlet name.
  [Cmdlet(VerbsCommunications.Send, "Greeting")]
  public class SendGreetingCommand : Cmdlet
  {
    // Declare the parameters for the cmdlet.
    [Parameter(Mandatory=true)]
    public string Name
    {
      get { return name; }
      set { name = value; }
    }
    private string name;

    // Override the ProcessRecord method to process
    // the supplied user name and write out a
    // greeting to the user by calling the WriteObject
    // method.
    protected override void ProcessRecord()
    {
      WriteObject("Hello " + name + "!");
    }
  }
}
Paste in sample code into the class1.cs file
Paste in sample code into the class1.cs file

Now that we have the code pasted in, we just need to build the solution. Click the Build menu and select Build Solution.

Build the powershell cmdlet dll file in visual studio
Build the powershell cmdlet dll file in visual studio

The build should complete successfully. Note the location of the .DLL file created.

Powershell cmdlet dll file build completes successfully in visual studio
Powershell cmdlet dll file build completes successfully in visual studio

Now, import the .DLL file that was created, using the cmdlet:

import-module <path to .DLL file>

After importing the .DLL file, you can now launch the newly created cmdlet in PowerShell! Cool stuff.

Import module and test the new powershell sample cmdlet
Import module and test the new powershell sample cmdlet

Wrapping up

Learning how to write a cmdlet in PowerShell is not too difficult. It is good practice to go through using the provided sample code from Microsoft to quickly build a .DLL file representing the new cmdlet. After importing the .DLL file, the cmdlet is immediately useable. This same process should work for any other cmdlet you want to create using C# code in Visual Studio.

Subscribe to VirtualizationHowto via Email 🔔

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Brandon Lee

Brandon Lee is the Senior Writer, Engineer and owner at Virtualizationhowto.com and has over two decades of experience in Information Technology. Having worked for numerous Fortune 500 companies as well as in various industries, Brandon has extensive experience in various IT segments and is a strong advocate for open source technologies. Brandon holds many industry certifications, loves the outdoors and spending time with family.

Related Articles

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.