powershell - Why is the value of "switch" type parameter passed to a string parameter? -
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 set $content
$null
, or ""
, or without default value, output same.
so why $content
take value $flag
?
@petseral indicated misunderstanding is, maybe bit brief, i'll elaborate little more.
a [switch]
parameter doesn't take value regular parameters. set true or false respectively providing or omitting parameter:
ps c:\> get-content .\test.ps1 param( [string]$content = $null, [switch]$flag ) $flag.ispresent $content ps c:\> .\test.ps1 false ps c:\> .\test.ps1 -flag true
alternatively can explicitly pass value putting colon between switch parameter , value:
ps c:\> .\test.ps1 -flag:$false false ps c:\> .\test.ps1 -flag:$true true
whitespace after colon allowed, not before (-flag: $false
passes $false
switch value, -flag :$false
doesn't).
if try assign switch value without colon value passed next parameter in line, in case -content
parameter:
ps c:\> .\test.ps1 -flag $false true # value of parameter $flag false # value of (positional) parameter $content ps c:\> .\test.ps1 -flag -content $false true # value of parameter $flag false # value of (named) parameter $content
if use -flag $true
(without colon) and pass value (named) parameter -content
value $true
passed unnamed third parameter (accessible via automatic variable $args
), same if put value @ end of statement:
ps c:\> get-content .\test2.ps1 param( [string]$content = $null, [switch]$flag ) $flag.ispresent $content $args[0] ps c:\> .\test2.ps1 -flag $false -content 'something' true false # $false passed unnamed 3rd parameter ps c:\> .\test2.ps1 -flag:$false -content 'something' false # $false passed explicit value of switch parameter $flag ps c:\> .\test2.ps1 -flag -content 'something' $false true false # $false passed unnamed 3rd parameter
Comments
Post a Comment