Powershell CmdLets

Powershell is a powerful language and can be used in several situations.
One of these situations is the deployment process (continuous delivery). It is also integrated in several systems, f.e. NuGet. NuGet uses powershell for post package installation processing.

I use powershell for the following cases (in continuous delivery):

  •  Replace/rename config files
  • Replace variables in config files
  • Call/Post to webservices
  • Run SQL commands

Note: External Modules need to be imported for calling webservices and running SQL commands. This can be done by calling the Import-Module CmdLet.

Powershell can be used as scripting language, but you can also create CmdLets. These commands can be invoked from the command line in the powershell environment.

CmdLet

A CmdLet is a command which can be called from the powershell command line.

Cmdlets are created by inheriting your class from Cmdlet.
This is available in the System.Management.Automation namespace.

CmdLets use the Verb-Noun naming convention. The Verb and Noun are provided as argument in the CmdLet attribute which decorates your CmdLet class.
The VerbsCommunications class comes with the following fields:

  • Connect
  • Disconnect
  • Read
  • Receive
  • Send
  • Write

You are not restricted to these Verbs, you can also use custom Verbs.

The ProcessRecord method is called. The method is called for every item in the pipeline.

[Cmdlet(VerbsCommunications.Send, "Greeting")]
public class SendGreetingCommand : Cmdlet
{
	[Parameter(Mandatory=true)]
	public string Name { get; set; }

	protected override void ProcessRecord() 
	{
	      WriteObject("Hello " + name + "!");
	}
}

This CmdLet example can be called from powershell command line as follows:

Send-Greeting –Name "Vincent" // Outputs: Hello Vincent!

Command line arguments are automatically bound to properties which are decorated with the Parameter attribute. Parameters are mandatory when the Mandatory argument of Parameters are set to true.

Maybe it’s interesting to know that the package manager console in Visual Studio also uses powershell and commands like Add-Migration and Update-Database are all CmdLets.

So if you haven’t given powershell a try, you really should!

The following two tabs change content below.
I'm a software developer from Utrecht. Interested in DDD, continuous delivery, new technologies & frameworks.

Latest posts by Vincent Keizer (see all)

Leave a Reply

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