Prohibiting Positional Parameters

by Nov 23, 2016

When you create PowerShell functions, parameters can be named or positional. Here is an example:

If you’d like to detect illegal characters in file paths, here is a slight adaption:

function Test-Command
{
  param
  (
    [string]$Name,
    [int]$Id
  )
  
  "Name: $Name ID: $ID"
}

Test-Command -Name Weltner -Id 12
Test-Command Weltner 12

As you can easily spot, using positional parameters (just specifying arguments, no explicit parameter names) may be more convenient in ad-hoc code, but much harder to read in script code. This is possible because the syntax of above function looks like this:

Test-Command [[-Name] <string>] [[-Id] <int>]

So how would a PowerShell function do the opposite, and create a function with this syntax:

Test-Command [-Name <string>] [-Id <int>] [<CommonParameters>]

It is by far not obvious, but entirely possible:

function Test-Command
{
  param
  (
    [Parameter(ParameterSetName='xy')]
    [string]$Name,
    
    [Parameter(ParameterSetName='xy')]
    [int]$Id
  )
  
  "Name: $Name ID: $ID"
}

Once you start working with parameter sets, all parameters are named by default.

Twitter This Tip! ReTweet this Tip!