0

I am very new to Powershell and coding. To my understanding, the input from a Read-Host cmdlet can be piped into a variable. I would like prompt the user to enter a number greater than 5 If -gt 5 it Write-Host Yes elseif -lt 5 no. For some reason no matter what number I select I get no. If goes straight to elseif. Can anyone help?

$A = Read-Host "Enter number greater than 5"

If ($A -gt 5)
{
Write-Host "yes"
}
elseif ($A -lt 5)
{
Write-Host "no"
}
melpomene
  • 84,125
  • 8
  • 85
  • 148
QTillmon
  • 1
  • 1
  • 3
    `Read-Host` gives you a string. You're comparing two unlike types. Consider this: `[int](Read-Host -Prompt 'message')` – Maximilian Burszley Oct 19 '18 at 00:17
  • Read-Host always creates a string variable. If you like to get a number you have to cast the variable explicitly as this like so `[INT]$A = Read-Host "Enter number greater than 5"` par example. – Olaf Oct 19 '18 at 00:18

1 Answers1

0

Putting TheIncorrigible1s comment into a full example.

Read-Host takes the input as a string and cannot figure out if it is greater than or lower than another string. example: Is Phone greater than Spectacles?

PowerShell is interpreting the input as "Is One greater than Seven?" and not "Is 1 greater than 7?"

Numbers vs words.

Adding the [int] in front of the Read-Host will convert the input into an integer. This means that if you try typing text, it will error out. It will only accept numerical input.

$A = [int](Read-Host "Enter number greater than 5")

If($A -gt 5) {
    "Yes" | Out-host
} elseif($A -lt 5) {
    "No" | Out-host
}

Note: I rather Out-Host instead of Write-Host. Each to their own though.

Drew
  • 3,814
  • 2
  • 9
  • 28
  • Thank you, Drew. I understand your examples especially the words vs numbers one. What is the benefit of Out-Host over Write-Host? – QTillmon Oct 21 '18 at 15:40