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
?
Give this test code a run, calling it as you did in the question. Add this test:
Script will illustrate the following points:
$false
unless specified on the command line. So-flag
sets the$flag
switch to true;-flag $true
sets the flag to true and passes the argument$true
to content.$flag=$false
in script params$content
is empty/null as there is also no need for$content=$null
@PetSerAl already indicated what your misunderstanding is, but maybe it was a bit too brief, so I'll elaborate a little more.
A
[switch]
parameter doesn't take a value like regular parameters. You normally set it to true or false respectively by providing or omitting the parameter:Alternatively you can explicitly pass a value by putting a colon between switch parameter and value:
Whitespace after the colon is allowed, but not before (
-Flag: $false
passes$false
as the switch value,-Flag :$false
doesn't).If you try to assign the switch value without the colon the value is actually passed to the next parameter in line, in your case the
-Content
parameter:If you use
-Flag $true
(without the colon) and pass a value to the (named) parameter-Content
the value$true
is passed as an unnamed third parameter (accessible via the automatic variable$args
), same as if you put the value at the end of the statement: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.