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

Please tell me that I have a subtle error in my code and that this is actually not how Powershell works.

$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 " This is impossible ." But this is so if $ in is an empty string. Thus, in Powershell, it appears that an empty string and a null string are considered equivalent in a switch , but not in an if . This is so confusing and is one of the main reasons many people shy away from using Powershell.

Can someone enlighten me why this is so? Does anyone know what the switch really does behind the scenes? This, of course, does not make a direct comparison.

+6
source share
3 answers

Powershell automatically sets an empty string to $ null. Therefore, when using $ null to invoke the .NET API, Powershell actually passes it to an empty string. To pass the actual NULL value in an API call, use [NullString] :: Value instead.

+8
source

I think this is a powershell 2.0 bug (here is some info on MSFT Connect ).

I can say that in version 3.0 you return the code out here!

+5
source

The following statements show that $null not equivalent to the empty string in the switch statement.

 $a=""; switch ($a){$null {"null"} "" {"empty string"}} $a=$null; switch ($a){$null {"null"} "" {"empty string"}} 
0
source

Source: https://habr.com/ru/post/927454/


All Articles