2019-09-13

PowerShell function switch parameter

I played a little with switch parameters to a PowerShell function. The initial purpose was to see how to use default values on switch parameters.
A quick (and dirty) function to test various usages of a switch parameter:

function Test-Switch {
    param (
        [Parameter(Mandatory=$true)][switch]$SwitchOne,
        [switch]$SwitchTwo = $false
    )
 
    if($SwitchOne) { 'One is True' }
    else { 'One is False' }

    if($SwitchTwo) { 'Two is True' }
    else { 'Two is False' }
}


I call the function in different ways like this:

'--- (true) (none) ---'
Test-Switch -SwitchOne
'--- false (none) ---'
Test-Switch -SwitchOne:$false
'--- (true) (false) ---'
Test-Switch -SwitchOne -SwitchTwo
'--- false true ---'
Test-Switch -SwitchOne:$false -SwitchTwo:$true
'--- (true) false ---'
Test-Switch -SwitchOne -SwitchTwo:$false


And the output is:

--- (true) (none) ---
One is True
Two is False
--- false (none) ---
One is False
Two is False
--- (true) (false) ---
One is True
Two is True
--- false true ---
One is False
Two is True
--- (true) false ---
One is True
Two is False


When I take a step back the functionality with a binary switch parameter to a PowerShell function is a nice feature.
But it should be used with caution.
Remember the principle to check for positives. So a usage of a false default I would consider more than twice.

No comments: