Using Named Parameters in PowerShell Functions

by | November 22,2016

Table of Contents

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:

Example of a Classic Function Declaration

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>]

Impact of Adding the “Position” Attribute to Parameters

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>]

How Positional and Named Parameters Differ

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!