Using Switch Parameters

by Jun 26, 2009

Switch parameters work like a switch, so they are either "on" or "off" aka $true or $false.

To add a switch parameter to a function, cast the parameter to [switch] like this:

function test([switch]$force) {
$force
}

When you call the function like this and omit the switch:

test

then $force will be $false. When you specify the switch, $force will be $true:

test -force

If you need the opposite result and want $force to be $true when it is omitted, simply turn the result around:

function test([switch]$force) {
$force = -not $force
$force
}

Now, when you call test -force, $force will be $false.