Please tell me that I've got a subtle mistake in my code here and that this is not actually the way that Powershell operates.
$in = ""
if ($in -ne $null)
{
switch ($in)
{
$null { echo "This is impossible" }
default { echo "out here!" }
}
}
All good, honest logic says that this script should never print out "This is impossible". But it does, if $in is an empty string. So in Powershell it would appear that an empty string and a null
string are considered equivalent in a switch
statement but not in an if
statement. This is so confusing and is one of the main reasons many people shy away from using Powershell.
Can anyone enlighten me as to why this is the case? Does anyone know what switch is actually doing behind the scenes? It's certainly not doing a straight -eq comparison.
Powershell auto-magically casts a $null to an empty string. Consequently, when using $null on a .NET API call, Powershell actually casts it to an empty string. To pass an actual null value in an API call, use [NullString]::Value instead.
I think is a bug of powershell 2.0 (here some info on MSFT Connect).
I can say that in v 3.0 you code return out here!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With