I have to say I’m generally impressed with the quality of submissions to this year’s Scripting Games. But there is a recurring concept that some people are using and I think there’s a better way. Some contestants are defining function or script parameters as booleans. But I believe they really should be using the [switch] type. Let me show you why.
ManageEngine ADManager Plus - Download Free Trial
Exclusive offer on ADManager Plus for US and UK regions. Claim now!
Very often, a function has a parameter, that if true generally means do X. Here’s a simple example.
Function Test-Bool { Param([string]$r=1,[bool]$log) $pi=[math]::pi $area=$pi * ($r*$r) $msg="A circle with a radius of $r has an area of $area" if ($log) { $msg | Tee-object -filepath $env:temp\log.txt write-host "Results Logged" -ForegroundColor Green } else { $msg } } #end function
When the function is run, the intent is that –log should indicate to record the result. If you don’t specify –log, the script runs just fine. But if you want to use –log and indicate that yes, you do want a log, you need to explicitly provide a boolean value
PS C:\> Test-Bool –r 3 –log:$True
Here are some examples:
Yes, technically it works but it feels clumsy in my opinion. Here’s the same function rewritten using [switch].
Function Test-Switch { Param([string]$r=1,[switch]$log) $pi=[math]::pi $area=$pi * ($r*$r) $msg="A circle with a radius of $r has an area of $area" if ($log) { $msg | Tee-object -filepath $env:temp\log.txt write-host "Results Logged" -ForegroundColor Green } else { $msg } }
When used this way, if the parameter has been specified, the effect is the same as specifying $True.
PS C:\> Test-Switch –r 4 -log
Does this make sense? For those of you who have used [bool] as a parameter type is this more of what you had in mind? Using [switch] seems cleaner and simpler to me. I was trying to come up with a good example of where [bool] makes sense, but I can’t come up one. If you have a use case, please share.
Using [bool] within a script or function is a different matter. I’m merely focusing on the type when used to define a parameter.
I actually ran into this exact scenario writing my Adv #2 script. I did a little googling and concluded the best way was with the [switch]. Good choice it seems!
Is there a difference between the switch and a bool with a default of $false ?
You are correct that there really isn’t a difference. However, you still need to specify the boolean value.
function Test-A {
Param([string]$name=”Jeff”,[bool]$test=$false)
if ($test) {
write-host “testing” -ForegroundColor Magenta
}
write-host $name
}
Test-A -test:$true
As I wrote in the post, I find using Switch a bit more elegant.
function Test-B {
Param([string]$name=”Jeff”,[switch]$test)
if ($test) {
write-host “testing” -ForegroundColor Magenta
}
write-host $name
}
Test-B -test
Or was there some other use case you had in mind?