Using Named Parameters in PowerShell Functions

by Nov 22, 2016

When you create a PowerShell function, all parameters are positional until you start adding the “Position” attribute. Once you start to do this, all parameters with no “Position” are suddenly named and must be specified. Have a look:

Here is a classic function declaration, producing three positional parameters:

function Test-Command
{
  param
  (
    [string]$Name,
    [int]$ID,
    [string]$Email
  )
  
  # TODO: Code using the parameter values
}

The syntax looks like this:

Test-Command [[-Name] <string>] [[-ID] <int>] [[-Email] <string>]

Once you add “Position” attributes to at least one parameter, the others become named:

function Test-Command
{
  param
  (
    [Parameter(Position=0)]
    [string]$Name,
    [Parameter(Position=1)]
    [int]$ID,
    [string]$Email
  )
  
  # TODO: Code using the parameter values
}

And here is the syntax:

Test-Command [[-Name] <string>] [[-ID] <int>] [-Email <string>] [<CommonParameters>]

What is the difference? You do not need to specify the parameter names -Name and -ID, but you must specify -Email if you want to submit a value to this third parameter. In the first example, all three parameters could be used positionally.

Twitter This Tip! ReTweet this Tip!