PowerShell: How to Check if Number is Within a Range


You can use the following syntax in PowerShell to check if a number is within a specific range:

(($num -ge 10) -and ($num -le 20))

This particular example checks if the number stored in the variable named $num is between 10 and 20 and returns either True or False as a result.

Note that the -ge operator is used for “greater than or equal to” logic while the -le operator is used for “less than or equal to” logic.

You could also use an if else statement to output specific text as a result:

if (($num -ge 10) -and ($num -le 20)) {
  Write-Host "Number is between 10 and 20" 
} else {
  Write-Host "Number is not between 10 and 20"
}

The following example shows how to use this syntax in practice.

Example: How to Check if Number is Within a Range in PowerShell

Suppose we have a variable named $num with a value of 17 in PowerShell.

We can use the following syntax to check if this value is between 10 and 20:

$num = 17

(($num -ge 10) -and ($num -le 20))

The following screenshot shows how to use this syntax in practice:

PowerShell check if number is in range

This returns True since the variable named $num does contain a value between 10 and 20.

We could also use an if else statement to return specific output:

$num = 17

if (($num -ge 10) -and ($num -le 20)) {
  Write-Host "Number is between 10 and 20" 
} else {
  Write-Host "Number is not between 10 and 20"
}

The following screenshot shows how to use this syntax in practice:

PowerShell if else statement to check if number is between range

This returns “Number is between 10 and 20” since the value of the variable is indeed within this range.

Feel free to replace 10 and 20 with any numbers that you would like, depending on the range that you’d like to use.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Round Numbers Up or Down
PowerShell: How to Round Numbers to 2 Decimal Places
PowerShell: How to Generate Random Number Between Range
PowerShell: How to Randomize Elements in an Array

Leave a Reply