Powershell: switch is not boolean

I spent a lot of time on this, mostly because of the lack of documentation on Powershell, I wonder why there isn’t one like for C#.

Anyway, back to the title, 2 different words, their behavior in a function is the same, but the invocation is not. Let me show you:

function MyAwesomeFunction
{
    param
    (
        [string] $foo,
        [string] $bar,
        [switch] $someVariable 
    )

    Write-Host "someVariable = $someVariable"

    if($someVariable)
    {
        Write-Host $foo
    }
    else
    {
        Write-Host $bar
    }
}

MyAwesomeFunction -foo "Foo" -Bar "Bar" 

Invocation of this script yields the following result:

PS D:\Personal\Desktop> D:\Personal\Desktop\test.ps1
someVariable = False
Bar

Now if we change the ‘switch’ on line 7 to ‘bool’:

function MyAwesomeFunction
{
    param
    (
        [string] $foo,
        [string] $bar,
        [bool] $someVariable #or boolean
    )

    Write-Host "someVariable = $someVariable"

    if($someVariable)
    {
        Write-Host $foo
    }
    else
    {
        Write-Host $bar
    }
}

MyAwesomeFunction -foo "Foo" -Bar "Bar" 

The result is the following

PS D:\Personal\Desktop> D:\Personal\Desktop\test.ps1
someVariable = False
Bar

Right, the same. Both times the variable ‘someVariable’ is False.

However, when we want to set the variable ‘someVariable’, then the invocation differs. If we invoke it like this on the bool version:

MyAwesomeFunction -foo "Foo" -Bar "Bar" -someVariable $true

That works fine.

If we invoke that one on the switch version, we are presented with the following error:

Positional argument error

So I would suggest that you use the bool version for internal functions in modules, ones that when you can explicitly set the someVariable to true or false, whereas the switch version is more useful of external use when you’re invoking a module and want to print more messages (like -Verbose), no need to print -Verbose $true.

Have a good one,

-Kristof

4 replies on “Powershell: switch is not boolean”

  1. You can use the colon syntax to set the value of a switch parameter.

    MyAwesomeFunction -foo “Foo” -Bar “Bar” -someVariable:$true

  2. this is the worse conclusion to this blog post. So does Scott’s comment on how to properly set the boolean value in the switch change your conclusion?

  3. Edit this post, it it misinformation as outlined by @scott_munro:disqus
    If you use the correct switch syntax as designed for the language there are no issues:

    # switch on it’s own sets to true
    PS C:UsersJason> MyAwesomeFunction “a” “b” -someVariable
    someVariable = True
    a

    # switch with $false set
    PS C:UsersJason> MyAwesomeFunction “a” “b” -someVariable:$false
    someVariable = False
    b

    # switch with $true set
    PS C:UsersJason> MyAwesomeFunction “a” “b” -someVariable:$true
    someVariable = True
    a

Comments are closed.