Tales from the code review…
How do you test for a switch type in a PowerShell script?
How do you test for the *absence* of a switch in a PowerShell Script?
Came across this recently, and decided to dig into it further.
Script:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Function Test-Switch ( [switch] $Test ) { | |
# Correct use of a switch Test (True case) | |
if ( $test ) { | |
"Do Something" | |
} | |
# Bad use of a switch test (False case) | |
if ( $test -eq $null ) { | |
"Never going to do it!" | |
} | |
# Better use of a switch test (False case) | |
if ( -not $test ) { | |
"Don't do it" | |
} | |
} | |
Test-Switch | |
Test-Switch –Test:$False | |
Test-Switch –Test | |
Test-Switch –Test:$True |
IN the example above, We have a function with a single switch argument. We then test against that argument, displaying “do something” if it’s set, and “Don’t do it” if not set.
Example Output:
PS C:\Users\Keith> C:\Users\Keith\Source\Example\test-switches.ps1 Don't do it Don't do it Do Something Do Something
Cool! Um… where did the “Never going to do it!” go? Well turns out that even when we don’t specify -test as an argument to the function, it’s still a switch defined as IsPresent = $false. So testing to see if it’s equal to $null will always fail, because it’s never $null.