2

I have a program and I'm simply trying to check for a negative number but it is not liking it. Have any tips?

$numbers = @(0,1,2,3,4,5,6,7,8,9,-1,-2,-3,-4,-5,-6,-7,-8,-9)
$number = Read-Host "Please input a number: " 
if ($number -le 0)
    {
        Write-Output "Thanks for using the program! Exitting now..."
        $finished = 1
    }
    elseif ($number -notin $numbers)
    {
        Write-Error "Input must be numeric"
        continue
    }
    else
    {
        Write-Host "Good number!"
    }
OysterMaker
  • 259
  • 2
  • 10
  • 25

1 Answers1

6

Read-Host produces [string] output, so you're actually doing a string comparison, and not getting the result you expect. Cast $number to [int] to do a mathematical comparison:

if ([int]$number -le 0)
Matt
  • 42,566
  • 8
  • 67
  • 104
mjolinor
  • 62,812
  • 6
  • 108
  • 130