[NoBrainer] Use splatting to simplify Cmdlet development

When rolling your own Cmdlets you will probably want to expand your module over time possibly adding or editing functions. I order to keep your Cmdlet as a function and not having to reload the module on every code change you can use Splatting (which requires at least PowerShell v3) to simplify developement and debugging. All you have to do is create a new script file (possibly with the same name as the Cmdlet) and move your existing Cmdlet into that file (or create a completely new Cmdlet altogether). Then add an additional PARAM block to the top of your script file and make a call to the Cmdlet at the end of the script file. By using the ‘splatting operator’ you can now pass all given parameters to the Cmdlet without having to retype them. Once you are finished you can move the function (back) into your module:

# New-Cmdlet.ps1
PARAM (
  [Parameter(Mandatory = $true, Position = 0)]
  [string] $s1
  ,
  [Parameter(Mandatory = $false, Position = 1)]
  [int] $i1
  ,
  [Parameter(Mandatory = $false, Position = 2)]
  [string] $s2 = 'some default value'
)

function New-Cmdlet {
PARAM (
  [Parameter(Mandatory = $true, Position = 0)]
  [string] $s1
  ,
  [Parameter(Mandatory = $false, Position = 1)]
  [int] $i1
  ,
  [Parameter(Mandatory = $false, Position = 2)]
  [string] $s2 = 'some default value'
)
  # do something useful

  # use $s1, $s2, $i1 as usual
  return $PSBoundParameters

} # function

# Call actual Cmdlet with all the parameters passed on from the cmdline
return New-Cmdlet @PSBoundParameters

With this approach you can call your function from the cmdline the same way as you would call it as a Cmdlet but do not have to alter your function body. Just keep in mind to alter the script PARAM block in case you change the signature of your Cmdlet while testing and that default values on parameters are not considered as ‘PSBoundParameters’ (but this is actually no problem as you are using exactly the same signature anyway). Once more, PowerShell rocks …

Trackbacks

  1. […] As a side note: parameter passing to the original Write-Progress Cmdlet is performed via the Splatting operator that I recently used to describe a method for easy Cmdlet development. […]

  2. […] every parameter explicitly I used Splatting (which we already described in a previous post Use splatting to simplify Cmdlet development) to pass the parameters to the script. So you still have to define a hashtable once, but this comes […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: