Why is the value of "switch" type parameter passed to a string parameter?

Viewed 27890

The test code (test.ps1):

Param(
    [string]$content = $null,
    [switch]$flag = $false
)
Write-Host $content

Output:

PS C:\Users\powershell> .\test.ps1

PS C:\Users\powershell> .\test.ps1 -flag $true    
True
PS C:\Users\powershell> .\test.ps1 -flag $false
False
PS C:\Users\powershell> .\test.ps1 -flag $true -content "lalala"
lalala

No matter I set $content to $null, or "", or without any default value, the output is the same.

So why does $content take the value from $flag?

3 Answers

I will add to this that you can assign the value via splatting as well, changing the value via the splat parameter assignment from $true to $false will alter your switch 'detection'. This is useful when you are using another value or property to determine if a switch should be used or not.

function FooBar {
    param (
        [switch]
        $Foo
    )
    if ($Foo){
        "Foo"
    }
    else{
        "Bar"
    }
}
$splat = @{
    Foo = $False
}
FooBar @splat
Related