PowerShell Code Smells: Boolean Parameters

This is a real quick one. In PowerShell, the “native” way to express a two-state variable is with Switch parameters.

For instance:

function Test-Thing{
Param([switch]$Recurse)
  #Code goes here

When calling Test-Thing, you can either supply -Recurse or leave it off. It’s a flag.

This is PowerShell 101.

Programmers coming from other languages are used to Boolean variables. Sometimes, one slips through and makes its way into a parameter list.

It’s not incorrect to have a Boolean parameter. It works just fine, but when I see one it makes me wonder what other PowerShell idioms the writer is not aware of. To me, a Boolean parameter is a code smell.

I mention this because I spotted one in Invoke-SQLCmd this week. [And no, I’m not piling on Invoke-SQLCmd. A co-worker was having problems with Invoke-SQLCmd and asked me to take a look. This was one of the problems]

The -OutputSqlErrors parameter for Invoke-SQLCmd is a Boolean. That means if you want to see SQL errors, you need to pass -OutputSQLErrors $true, rather than just -OutputSQLErrors.

Interestingly enough, there are 8 switch parameters on this cmdlet. This is the only Boolean.

What do you think? Do you ever see parameters like this?

Let me know in the comments.

–Mike

2 Comments

  1. When I started writing PowerShell functions, I would do this all the time. But when I finally got a clue, I stopped and never looked back. The fact that some parameters are Boolean and some are switches makes me think that they were all Boolean at one point and were then converted to switch parameters and one fell through the cracks. Just guessing here.

    • You’re probably right. One thing I can’t say enough is that everyone’s code (mine included) has some kind of code smell. The older the code, the more likely that there will be some.

Comments are closed.