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 …
2 Comments »