The difference between [Switch] and[Bool] in Powershell function parameters


#switch parameter
cls
function MyAwesomeFunction1
{
[CMDLetBinding()]
param
(
[string] $foo,
[string] $bar,
[switch] $someVariable
)

Write-Host "someVariable = $someVariable" + $someVariable.GetType()

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

#boolean parameter
function MyAwesomeFunction2
{
[CMDLetBinding()]
param
(
[string] $foo,
[string] $bar,
[bool] $someVariable
)

Write-Host "someVariable = $someVariable" + $someVariable.GetType()

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

MyAwesomeFunction1 -foo "foo" -bar "bar" -someVariable:$true
MyAwesomeFunction1 -foo "foo" -bar "bar" -someVariable:$false
MyAwesomeFunction1 -foo "foo" -bar "bar" -someVariable
MyAwesomeFunction1 -foo "foo" -bar "bar"

MyAwesomeFunction2 -foo "foo" -bar "bar" -someVariable $true
MyAwesomeFunction2 -foo "foo" -bar "bar" -someVariable $false
MyAwesomeFunction2 -foo "foo" -bar "bar" -someVariable
MyAwesomeFunction2 -foo "foo" -bar "bar"


Comments (4)

  1. Same result for both methods despite they are of different type…

    1. Bulent Ozkir says:

      Very similar. But did you notice the : next to the parameters for switch call? 🙂 That is the main difference for the consumer for Switch parameter.

      1. Also omitting the switch is equivalent to switch=$true.
        What happens if you don’t specify the boolean variable in your command-line?

        1. Bulent Ozkir says:

          I updated the code to reflect all variations you asked for. The output is below:

          someVariable = True + System.Management.Automation.SwitchParameter
          foo
          someVariable = False + System.Management.Automation.SwitchParameter
          bar
          someVariable = True + System.Management.Automation.SwitchParameter
          foo
          someVariable = False + System.Management.Automation.SwitchParameter
          bar
          someVariable = True + System.Boolean
          foo
          someVariable = False + System.Boolean
          bar
          MyAwesomeFunction2 : Missing an argument for parameter 'someVariable'. Specify a parameter of
          type 'System.Boolean' and try again.
          At line:51 char:42
          + MyAwesomeFunction2 -foo "foo" -bar "bar" -someVariable
          + ~~~~~~~~~~~~~
          + CategoryInfo : InvalidArgument: (:) [MyAwesomeFunction2], ParameterBindingExcep
          tion
          + FullyQualifiedErrorId : MissingArgument,MyAwesomeFunction2

          someVariable = False + System.Boolean
          bar

Skip to main content