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
  • 279
  • 2
  • 13
  • 26

1 Answers1

7

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
  • 45,022
  • 8
  • 78
  • 119
mjolinor
  • 66,130
  • 7
  • 114
  • 135