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

Question:

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.

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.

Answer:

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!

Source:

Powershell treats empty string as equivalent to null in switch statements but not if statements by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply