Using Arrays as Parameter Default Values

by Feb 27, 2015

PowerShell 3.0 and later

If you define a PowerShell function with some parameters, and you want a given parameter to have a default value that is an array, you may run into a syntax problem:

function Get-SomeData
{
  param
  (
    $ServerID = 1,2,5,10,11
  )

  "Your choice: $ServerID"
}

PowerShell uses commas to separate parameters, so the comma after the number “1” in your param() block is misinterpreted, and PowerShell thinks that a new parameter definition follows.

Whenever there is room for misinterpretation, use parenthesis to make sure which parts belong together. This is perfect valid code:

function Get-SomeData
{
  param
  (
    $ServerID = (1,2,5,10,11)
  )

  "Your choice: $ServerID"
} 

Twitter This Tip! ReTweet this Tip!