0

I have a weird issue occurring. I'm parsing a number from a name, which looks like this: ($env:COMPUTERNAME).Substring(11, 2). Said name is usually like abcxyzhij099w. I'm getting the 99 in that example. I then evaluate it using a series of -gt -lt calls, for example elseif ($time -ge 60 -and $time -lt 120).

My problem is that I'm currently evaluating the number 62. It successfully evaluates that it's less than 70, 99, and 620, but anything between 100 and 619 fails. I've included an image but I'm at a loss to why this would happen. Manually setting $time to 62 allows all checks to pass, but parsing from the name causes it to fail.

I've verified it's length is 2, and gm shows it as a system.string. I imagine I'm just missing something incredibly small but I haven't run into this before. Any assistance would be appreciated!

enter image description here

Nick
  • 1,178
  • 3
  • 24
  • 36

1 Answers1

7

PowerShell “casts” values on the right side of a comparison operator to match the type of the left-side value. Thus, you’re seeing the results of a string comparison. If you want a numeric comparison, try reversing the comparison (that is, instead of $time -lt 619, use 619 -gt $time), or force the left side operand to be numeric (e.g., [int]$time -lt 619).

Jeff Zeitlin
  • 9,773
  • 2
  • 21
  • 33
  • Thank you for the quick answer and explanation! I never knew that's how PS compared. This fixed my issue, I'll accept your answer as soon as it allows me to. Thank you!! – Nick Oct 24 '19 at 12:31