Powershell function argument default: Weirdness when it has a type constaint -
if have function parameter without type constraint:
> function ($s=$null) {if ($s -eq $null) {write-host "hi"} if ($s -eq "") {write-host "kk"}} > hi now if add type constraint it, $null interpreted differently:
> function ([string]$s=$null) {if ($s -eq $null) {write-host "hi"} if ($s -eq "") {write-host "kk"}} > kk i can't find doc explain this. it's not consistent.
in first example (function a), $s equivalent $null - it's null.
in second example (function b), because you're casting $s [string] object, it's empty string (equivalent [string]::empty), not $null.
you can check adding following each of functions:
if($s -eq [string]::empty){"empty!"}; only b print empty! - a evaluate $false
alternately, add this:
$s|get-member a throw error - same error you'll if run $null|get-member. b show $s string , list of members of class.
Comments
Post a Comment