Comparison Operators
Part of the PowerShell Basics section of Coddy's PowerShell journey. Lesson 12 of 28.
PowerShell compares with operators that start with a dash: -eq (equal), -ne (not equal), -gt (greater than), -ge (greater or equal), -lt (less than) and -le (less or equal). A comparison gives True or False:
$stock = 4
Write-Output ($stock -lt 5)
Write-Output ("Apple" -eq "apple")
Write-Output ("Apple" -ceq "apple")True
True
FalseText comparisons ignore case. Add a c for a case-sensitive one: -ceq, -cne. -like matches a pattern where * stands for any text: "notes.txt" -like "*.txt" is True.
Do not write > or <. In PowerShell, > sends output to a file, so $stock > 5 creates a file named 5 and compares nothing.
Challenge
EasyRead a whole number and print three facts about it.
- Read the number with the prompt
Numberand convert it with[int]. - Print
Positive:and whether the number is greater than 0. - Print
Even:and whether the number divides by 2 with no remainder. - Print
Over 100:and whether the number is greater than 100.
With the input 7, your script prints:
Number: 7
Positive: True
Even: False
Over 100: FalseWith -4, it prints Positive: False, Even: True and Over 100: False.
Try it yourself
$n = [int](Read-Host "Number")
# Print the three comparisons
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in PowerShell Basics
5Project: Password Checker
Project OverviewLength Check3Input And Conditions
Reading InputComparison OperatorsIf, ElseIf And ElseThe Switch StatementRecap - Ticket Price