Friday, 13. March 2009 16:56
Some things may seem a little strange when working with PowerShell when coming from other scripting languages and especially when coming from a development background. What I noticed today in one of my scripts took me quite a while to troubleshoot.
The problem concerned a comparison between two values using “-eq”. I retieved a value from a subroutine and compared it to a string value. The code looked something like this:
$returnValue = Somesubroutine(xxxx…
if ($returnValue -eq “xxxxxxx”) { do something }
Because of an error in my subroutine the returning value was a boolean instead of a string. Still I wondered why the “do something” was executed. I mean, $True can’t possibly equal “xxxxxxx” right? Try the following on your commandline:
if ($true -eq “blahblahblah”) {write-host “They are the same”}
Have you tried it? The text “They are the same” will actually be written to the console! How weird is that?
PowerShell has a very powerfull typing system. This typing (or casting if you will) will automagically convert the type of an object to an other type if needed. However, PowerShell should only do this IF NO INFORMATION IS LOST.
In this case I’m not sure what is happening. Either the text “blahblahblah” is actually converted to a boolean and since it exists it will be converted to $true. Or, the if statement encounters a “$true” and will then immediatly yield true and execute the command ‘write-host “They are the same”‘.
Whatever is the case: GOTCHA!