Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell treats empty string as equivalent to null in switch statements but not if statements

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.

like image 760
Richiban Avatar asked Oct 11 '12 12:10

Richiban


2 Answers

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.

like image 66
Bob M Avatar answered Sep 22 '22 22:09

Bob M


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!

like image 43
CB. Avatar answered Sep 20 '22 22:09

CB.