views:

33

answers:

1

Can someone explain to me why these comparisons work they way the do. I had a bug in one of my scripts that took me a little bit to work through. I was using read-host and typing a number. It was storing it as a string.

Write-Host "(`'2`' -gt 9 ) = " ('2' -gt 9 )
Write-Host "(2 -gt 9 ) = " (2 -gt 9 )
Write-Host "(`'2`' -gt 10 ) = " ('2' -gt 10 )

If you are comparing a string to an Int does it use the Ascii value? If so why does the first one show $false, it should be $true.

Then how is it when you change the int to 10 it becomes $true.

A: 

On comparison a right value is converted to the type of a left value. Thus, '2' -gt 9 becomes '2' -gt '9', that is False, and '2' -gt 10 becomes '2' -gt '10', that is True.

Roman Kuzmin
Roman can you point me to a link on how the strings compare with -gt, -lt and so forth. I understand the conversion process now but still confused on why '2' is greater then '10'.Thanks
Mike
I will try to rephrase. I think you are confused by *numbers* in strings but they are just characters. Forget about *numbers*, think *characters*. To make it easier replace 0->a, 1->b, 2->c and you will get "c" and "ba" analogues for "2" and "10". Now, "c" -gt "b" (alphabetically) just like "2" -gt "1". And any string starting with "c" is -gt any string starting with "b", e.g. "c" -gt "ba". The same is true for any string "2...." and "1....", for example "2" -gt "10".
Roman Kuzmin
Thank you, I think I was confused on how strings compare when you don't have the same number of characters on each side. It only compares the amount of characters that are on the left.
Mike

related questions