PowerShell Comparison Operators

These below are standard comparison operators used in PowerShell.

Example:

If ($Samples -eq "Scott"){
     Do Something
}

  • -eq (Equal To)

  • -ceq (for case-sensitive Compare)

  • -ne (not equal to)

  • -lt (less than)

  • -le (less than or equal to)

  • -gt (greater than)

  • -ge (greater than or equal to)

  • -like (like—a wildcard comparison)

  • -notlike (not like—a wildcard comparison)

  • -contains (contains the specified value)

  • -notcontains (doesn't contain the specified value)

  • -creplace (for case-sensitive replace)

 

 



EVALUATE COMPARISON to get a Boolean return of is String or is DateTime...

  • -is

  • -isnot

Example:
$String1 = "I am a String"

if ($String1 -is [String]){
         Write-Host "Is a String"
}Else{
         write-Host "Is Not a String"
}


 

 

 

DataTypes used for comparison:

[string] Fixed-length string of Unicode characters
[char] A Unicode 16-bit character
[byte] An 8-bit unsigned character

[int] 32-bit signed integer
[long] 64-bit signed integer
[bool] Boolean True/False value

[decimal] A 128-bit decimal value
[single] Single-precision 32-bit floating point number
[double] Double-precision 64-bit floating point number
[DateTime] Date and Time

[xml] Xml object
[array] An array of values
[hashtable] Hashtable object



COMPARISON LOGICAL OPERATORS to be used for multiple checks on Boolean.

  • -and

  • -or

  • -not

  • !

Example:
$String1 = "I am a String"
$Number = 4

if (($String1 -is [String]) -and ($Number -is [Int])){
       Write-Host "Is a String and a Integer"
}Else{
      write-Host "Is Not a String or Not a Number"
}

My Output:
Is a String and a Integer

2020 | Scott W. Head  |  Sr. Systems Admin | Certified Microsoft Windows Server Administrator