Bool vs Switch

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.

Very often, a function has a parameter, that if true generally means do X.  Here’s a simple example.

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:

test-bool

Yes, technically it works but it feels clumsy in my opinion. Here’s the same function rewritten using [switch].

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

 test-switch

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.

4 thoughts on “Bool vs Switch”

  1. 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!

    1. 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?

Comments are closed.