Assigning Values to Parameters

by Jun 30, 2009

Cmdlets and Functions most of the time support one or more parameters. Let’s take this simple function. It defines two parameters called number and force.

function test([Int]$number=0, [switch]$force) {
“You specified: number=$number, force=$force”
}

Note also that each parameter has been strongly typed: The function expects the number to be of type Integer and force to be a switch parameter – either present or not.

When you call “test” without specifying any parameter, the number defaults to 0 and the switch parameter force defaults to $false.

To specify parameters, either use positional parameters: simply submit the values in the order of the parameters:

test 100 $true

Or use named parameters. As you will quickly discover, switch parameters do not support position. They always need to be stated by name. When using named parameters, order does not matter anymore:

test 100 -force
test -number 100 -force
test -force -number 100

Note how switch parameters do not use a value. They are either present or not, and when they are present, they default to $true, else $false.

There is one little known exception. When you add a colon to a parameter name, you can assign a value to the parameter as well. Why would you do that? Both statements work the same:

test -number 100
test -number:100

A difference occurs with switch parameters. Since switch parameters do not accept a value, the following call would fail:

test -force $false

It would actually assign $false to the parameter $number, convert the Boolean to integer value 0 and set the force parameter to $true since the switch was present.

To bind a value to a switch parameter, use the colon like this:

test -force:$False

This explicitly sets force to $false. It is the same as if you had omitted the force switch altogether.