Skip to content

Operators

Note

Complete reference for PowerShell operators including arithmetic, comparison, logical, and assignment operators.

Overview

Operators are symbols that tell PowerShell to perform specific operations on values. You use them constantly for math, comparisons, logic, and assignments. PowerShell's operators are different from other languages - especially comparison operators which use -eq instead of ==.

Arithmetic Operators

Perform mathematical calculations:

+    # Addition
-    # Subtraction
*    # Multiplication
/    # Division
%    # Modulus (remainder)

Examples

# Basic math
10 + 5          # 15
20 - 8          # 12
4 * 7           # 28
15 / 3          # 5
17 % 5          # 2 (remainder)

# With variables
$a = 10
$b = 3
$sum = $a + $b          # 13
$difference = $a - $b   # 7
$product = $a * $b      # 30
$quotient = $a / $b     # 3.33333...
$remainder = $a % $b    # 1

# String concatenation (+ works with strings too)
"Hello" + " " + "World"  # "Hello World"
$firstName = "John"
$lastName = "Doe"
$fullName = $firstName + " " + $lastName  # "John Doe"

# Array concatenation
$array1 = 1, 2, 3
$array2 = 4, 5, 6
$combined = $array1 + $array2  # 1, 2, 3, 4, 5, 6

# Negative numbers
-5              # Negative 5
$x = 10
-$x             # -10

Comparison Operators

Compare values - returns $true or $false:

-eq     # Equal to
-ne     # Not equal to
-gt     # Greater than
-ge     # Greater than or equal to
-lt     # Less than
-le     # Less than or equal to

Case Sensitivity

By default, comparison operators are case-insensitive for strings. Add c prefix for case-sensitive: -ceq, -cne, etc.

Examples

# Numeric comparisons
5 -eq 5         # $true
10 -ne 5        # $true
10 -gt 5        # $true
10 -ge 10       # $true
5 -lt 10        # $true
5 -le 5         # $true

# String comparisons (case-insensitive by default)
"hello" -eq "HELLO"     # $true
"test" -ne "TEST"       # $false
"apple" -lt "banana"    # $true (alphabetical)

# Case-sensitive comparisons
"hello" -ceq "HELLO"    # $false
"hello" -ceq "hello"    # $true

# With variables
$age = 25
if ($age -ge 18) {
    Write-Output "Adult"
}

# Comparing null
$null -eq $myVar        # $true if $myVar is null or doesn't exist
$myVar -ne $null        # $true if $myVar has a value

Logical Operators

Combine multiple conditions:

-and    # Both conditions must be true
-or     # At least one condition must be true
-not    # Reverses true/false
!       # Also means NOT (same as -not)
-xor    # Exclusive OR (one true, one false)

Examples

# AND - both must be true
(5 -gt 3) -and (10 -lt 20)      # $true (both true)
(5 -gt 10) -and (10 -lt 20)     # $false (first is false)

# OR - at least one must be true
(5 -gt 10) -or (10 -lt 20)      # $true (second is true)
(5 -gt 10) -or (20 -lt 10)      # $false (both false)

# NOT - reverses the result
-not $true                       # $false
-not $false                      # $true
-not (5 -eq 10)                  # $true
!(5 -eq 10)                      # $true (! is same as -not)

# XOR - exactly one must be true
$true -xor $false               # $true
$true -xor $true                # $false
$false -xor $false              # $false

# Complex conditions
$age = 25
$hasLicense = $true

if (($age -ge 18) -and $hasLicense) {
    Write-Output "Can drive"
}

# Checking multiple conditions
$status = "Active"
if (($status -eq "Active") -or ($status -eq "Pending")) {
    Write-Output "Valid status"
}

Pattern Matching Operators

Match patterns in strings:

-like       # Wildcard matching (* and ?)
-notlike    # Does not match wildcard
-match      # Regex pattern matching
-notmatch   # Does not match regex

Wildcard Matching (-like)

# * matches any characters
"PowerShell" -like "Power*"         # $true
"test.txt" -like "*.txt"            # $true
"hello" -like "*ll*"                # $true

# ? matches single character
"test1" -like "test?"               # $true
"test12" -like "test?"              # $false (two chars)

# Case-sensitive variant
"PowerShell" -clike "power*"        # $false
"PowerShell" -clike "Power*"        # $true

# Practical example
$filename = "report_2025.csv"
if ($filename -like "*.csv") {
    Write-Output "This is a CSV file"
}

Regex Matching (-match)

# Basic patterns
"abc123" -match "\d+"               # $true (contains digits)
"hello@example.com" -match "@"      # $true
"test123" -match "^\d+$"            # $false (not all digits)

# Extracting matched text with $matches
"Error: File not found" -match "Error: (.+)"
$matches[1]  # "File not found"

"Server01" -match "Server(\d+)"
$matches[1]  # "01"

# Email validation (simple)
$email = "user@example.com"
if ($email -match "^[\w\.-]+@[\w\.-]+\.\w+$") {
    Write-Output "Valid email format"
}

# IP address pattern
$ip = "192.168.1.1"
if ($ip -match "^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$") {
    Write-Output "Looks like an IP address"
}

Containment Operators

Check if a value exists in a collection:

-contains       # Collection contains value
-notcontains    # Collection does not contain value
-in             # Value is in collection
-notin          # Value is not in collection

Examples

# Arrays
$colors = "Red", "Green", "Blue"

# -contains (collection -contains value)
$colors -contains "Red"         # $true
$colors -contains "Yellow"      # $false

# -in (value -in collection) - reversed syntax
"Red" -in $colors               # $true
"Yellow" -in $colors            # $false

# -notcontains
$colors -notcontains "Yellow"   # $true

# -notin
"Yellow" -notin $colors         # $true

# Practical example
$allowedUsers = "admin", "user1", "user2"
$currentUser = "user1"

if ($currentUser -in $allowedUsers) {
    Write-Output "Access granted"
} else {
    Write-Output "Access denied"
}

Assignment Operators

Assign values to variables:

=       # Assign
+=      # Add and assign
-=      # Subtract and assign
*=      # Multiply and assign
/=      # Divide and assign
%=      # Modulus and assign

Examples

# Basic assignment
$x = 10
$name = "John"

# Add and assign
$x = 10
$x += 5     # $x is now 15 (same as $x = $x + 5)

# Subtract and assign
$x = 20
$x -= 5     # $x is now 15

# Multiply and assign
$x = 10
$x *= 2     # $x is now 20

# Divide and assign
$x = 20
$x /= 4     # $x is now 5

# Modulus and assign
$x = 17
$x %= 5     # $x is now 2 (remainder)

# String concatenation
$message = "Hello"
$message += " World"    # $message is now "Hello World"

# Array addition
$numbers = 1, 2, 3
$numbers += 4           # $numbers is now 1, 2, 3, 4

Type Operators

Work with object types:

-is         # Is of specified type
-isnot      # Is not of specified type
-as         # Convert to specified type

Examples

# Check type
$x = 10
$x -is [int]        # $true
$x -is [string]     # $false

$text = "hello"
$text -is [string]  # $true
$text -isnot [int]  # $true

# Type conversion
$number = "123" -as [int]       # Converts string to int: 123
$text = 456 -as [string]        # Converts int to string: "456"

# Checking null
$null -is [object]              # $false
$myVar = $null
$myVar -is $null                # $false (incorrect - $null is not a type)
$null -eq $myVar                # $true (correct way to check null)

# Array type checking
$array = 1, 2, 3
$array -is [array]              # $true

# Practical example
function Process-Value {
    param($Value)

    if ($Value -is [int]) {
        Write-Output "Processing integer: $Value"
    } elseif ($Value -is [string]) {
        Write-Output "Processing string: $Value"
    } else {
        Write-Output "Unknown type"
    }
}

Replace Operator

Replace text in strings:

-replace    # Replace using regex pattern

Examples

# Basic replacement
"Hello World" -replace "World", "PowerShell"    # "Hello PowerShell"

# Remove text (replace with empty)
"test123" -replace "\d+", ""                    # "test"

# Replace multiple spaces with one
"too    many     spaces" -replace "\s+", " "    # "too many spaces"

# Case-insensitive by default
"HELLO" -replace "hello", "Hi"                  # "Hi"

# Case-sensitive variant
"HELLO" -creplace "hello", "Hi"                 # "HELLO" (no match)
"HELLO" -creplace "HELLO", "Hi"                 # "Hi"

# Practical examples
$filename = "my file (2).txt"
$clean = $filename -replace "[()]", ""          # "my file 2.txt"

$path = "C:\Temp\file.txt"
$path -replace "\\", "/"                        # "C:/Temp/file.txt"

# Remove special characters
$input = "Hello@#$World!"
$clean = $input -replace "[^a-zA-Z0-9\s]", ""   # "HelloWorld"

Split and Join Operators

Split strings into arrays or join arrays into strings:

-split      # Split string into array
-join       # Join array into string

Examples

# Split by delimiter
"apple,banana,cherry" -split ","                # Array: "apple", "banana", "cherry"
"one two three" -split " "                      # Array: "one", "two", "three"

# Split by regex pattern
"test123hello456world" -split "\d+"             # Array: "test", "hello", "world"

# Split with limit
"a,b,c,d,e" -split ",", 3                       # Array: "a", "b", "c,d,e"

# Join array into string
$fruits = "apple", "banana", "cherry"
$fruits -join ", "                              # "apple, banana, cherry"
$fruits -join " | "                             # "apple | banana | cherry"
$fruits -join ""                                # "applebananacherry"

# Practical examples
$path = "C:\Users\John\Documents\file.txt"
$parts = $path -split "\\"
$filename = $parts[-1]                          # "file.txt"

# CSV to array
$csv = "Name,Age,City"
$headers = $csv -split ","                      # Array: "Name", "Age", "City"

# Array to path
$pathParts = "C:", "Users", "John", "file.txt"
$fullPath = $pathParts -join "\"                # "C:\Users\John\file.txt"

Operator Precedence

When multiple operators are in one expression, PowerShell evaluates them in this order:

1. Parentheses ()
2. -not, !
3. *, /, %
4. +, -
5. Comparison operators (-eq, -ne, -gt, etc.)
6. -and
7. -or, -xor

# Examples
5 + 3 * 2           # 11 (multiplication first)
(5 + 3) * 2         # 16 (parentheses first)

$x = 10
-not $x -gt 5       # Error: unclear precedence
-not ($x -gt 5)     # $false (clear: $x > 5 is true, NOT makes it false)

# Always use parentheses for clarity
if (($age -ge 18) -and ($hasLicense -eq $true)) {
    # Clear intent
}

Common Use Cases

Use Case 1: Input Validation

function Validate-Input {
    param([string]$Input)

    # Check if not empty
    if (-not ($Input -eq "")) {
        # Check if numeric
        if ($Input -match "^\d+$") {
            $number = [int]$Input
            # Check range
            if (($number -ge 1) -and ($number -le 100)) {
                Write-Output "Valid input: $number"
                return $true
            }
        }
    }

    Write-Output "Invalid input"
    return $false
}

Use Case 2: File Extension Filtering

$files = Get-ChildItem -Path C:\Temp

foreach ($file in $files) {
    if ($file.Extension -in @(".txt", ".log", ".csv")) {
        Write-Output "Text-based file: $($file.Name)"
    } elseif ($file.Extension -like ".doc*") {
        Write-Output "Word document: $($file.Name)"
    }
}

Use Case 3: String Cleaning and Formatting

$rawInput = "  John.Doe@EXAMPLE.COM  "

# Clean up
$email = $rawInput.Trim()                       # Remove spaces
$email = $email.ToLower()                       # Lowercase
$email = $email -replace "\s+", ""              # Remove any spaces

# Validate
if ($email -match "^[\w\.-]+@[\w\.-]+\.\w+$") {
    Write-Output "Cleaned email: $email"
}

Tips & Tricks

PowerShell Uses Different Comparison Operators

# DON'T use these (they won't work)
if ($x == 5) { }        # Error!
if ($x != 10) { }       # Error!
if ($x > 5) { }         # Error!

# DO use these
if ($x -eq 5) { }       # Correct
if ($x -ne 10) { }      # Correct
if ($x -gt 5) { }       # Correct

-contains vs -in (Order Matters)

$array = 1, 2, 3

# -contains: collection -contains value
$array -contains 2      # $true

# -in: value -in collection
2 -in $array            # $true

# They do the same thing, just reversed syntax

Use Parentheses for Clarity

# Unclear
if ($x -gt 5 -and $y -lt 10 -or $z -eq 0) { }

# Clear
if ((($x -gt 5) -and ($y -lt 10)) -or ($z -eq 0)) { }

String Addition vs Number Addition

# These look similar but behave differently
"10" + "5"          # "105" (string concatenation)
10 + 5              # 15 (addition)
"10" + 5            # "105" (string wins, converts 5 to string)
[int]"10" + 5       # 15 (explicit conversion to int)

Null Comparisons

# WRONG order
$myVar -eq $null    # Sometimes doesn't work with arrays

# CORRECT order (always put $null first)
$null -eq $myVar    # Always works

Case Sensitivity

# Default: case-insensitive
"PowerShell" -eq "powershell"   # $true
"test" -like "TEST*"            # $true

# Use 'c' prefix for case-sensitive
"PowerShell" -ceq "powershell"  # $false
"test" -clike "TEST*"           # $false

Additional Resources