PowerShell Operators: Supercharge with 10 Amazing Methods

PowerShell Operators

PowerShell Operators are special symbol or keyword in the PowerShell scripting language that makes various actions easier. They act as “verbs” in PowerShell, manipulating data and allowing you to compare and control the logical flow of your script. These operators allow you to perform arithmetic calculations, evaluate conditions, assign variables, manipulate data types, and perform bites. Essentially, they are basic building blocks that allow users to create dynamic, automated solutions in their PowerShell environments.

PowerShell Operators

Types of Operator

PowerShell Operators

  1. Arithmetic Operators
  2. Assignment Operators
  3. Comparison Operators
  4. Logical Operators
  5. Redirection Operators
  6. Split and Join Operators


1. Arithmetic Operators

PowerShell mathematics operators are symbols that enable mathematical operations on numerical facts within PowerShell scripts. They facilitate simple calculations like addition, subtraction, multiplication, department, and modulo (the rest) operations.

  • + (Addition): Adds two numeric values.
  • – Subtraction): Subtracts one numeric value from another.
  • * (Multiplication): Multiplies two numeric values.
  • / (Division): Divides one numeric value by another.
  • % (Modulo): Returns the remainder after dividing one numeric value by another.

2. Assignment Operator 

Assignment operators in PowerShell are used to assign, change, or append values to variables. They simplify the process of storing and modifying data within your scripts.

Types of Assignment Operators:

  • = (Assignment): Assigns the value on the right to the variable on the left.
    Example: $x = 10
  • += (Add and Assign): Adds the right-hand value to the variable’s current value and assigns the result.
    Example: $x += 5 (equivalent to $x = $x + 5)
  • -= (Subtract and Assign): Subtracts the right-hand value from the variable’s current value and assigns the result.
    Example: $x -= 3 (equivalent to $x = $x – 3)
  • *= (Multiply and Assign): Multiplies the variable’s current value by the right-hand value and assigns the result.
    Example: $x *= 2 (equivalent to $x = $x * 2)
  • /= (Divide and Assign): Divides the variable’s current value by the right-hand value and assigns the result.
    Example: $x /= 4 (equivalent to $x = $x / 4)
  • %= (Modulo and Assign): Performs the Modulo operation on the variable’s current value and the right hand value, and assigns the result.
    Example: $x %= 3 (equivalent to $x = $x % 3)

 

3. Comparison Operators 

The PowerShell comparison operator is a symbol or keyword used to compare two values, returning a Boolean value that indicates the result of the comparison. These operators are crucial for implementing conditional logic, filtering data, and validating information.

PowerShell Operators

Equality Operators:

  • -eq: Equal to (case-insensitive):- Checks if two values are equal.
  • -ne: Not equal to (case-insensitive):- Checks if two values are not equal.
  • -ceq: Equal to (case-sensitive):- Checks if two strings are exactly equal including case.
  • -cne: Not equal to (case-sensitive):- Checks if two strings are not equal including case.

Matching Operators:

  • -like: Wildcard matching (case-insensitive):- Checks if a string matches a wildcard pattern.
  • -notlike: Wildcard not matching (case-insensitive):- Checks if a string does not match a wildcard pattern.
  • -match: Regular expression matching (case-insensitive):- Checks if a string matches a regular expression.
  • -notmatch: Regular expression not matching (case-insensitive) :- Checks if a string does not match a regular expression.

-clike, -cnotlike, -cmatch, -cnotmatch: These are the case sensitive versions of the above operators.

Containment Operators:

  • -contains: (Contains) :- Checks if a collection contains a specified value.
  • -notcontains (Does not contain) :- Checks if a collection does not contain a specified value.
  • -in: (In) :- Checks if a value is within a collection.
  • -notin: (Not in) : – Checks if a value is not within a collection.

Type Comparison Operators:

  • -is (Is of type) : – Determines if an object is of a particular .NET type.
  • -isnot (Is not of type) : – Determines if an object is not of a particular .NET type.

 

4. Logical Operator

PowerShell logical operators are symbols or keywords that manipulate Boolean values, allowing you to create compound conditions for decision-making within scripts.

Types of Logical Operators:

  • -and (Logical AND): – Returns $true only if both conditions on either side of the operator are $true.
    Example: ($a -gt 10) -and ($b -lt 20)
  • -or (Logical OR): – Returns $true if at least one of the conditions on either side of the operator is $true.
    Example: ($a -eq 10) -or ($b -eq 20)
  • -xor (Logical Exclusive OR): – Returns $true if only one of the conditions is $true. If both are $true or both are $false, it returns $false.
    Example: ($a -eq 10) -xor ($b -eq 20)
  • -not or ! (Logical NOT): – Negates a Boolean value. If a condition is $true, -not makes it $false, and vice versa.
    Example: -not ($a -eq 10) or !($a -eq 10)

5. Redirection Operators

PowerShell offers several redirection operators to manage command output effectively. Here are three commonly used ones:

1. > (Redirect Output – Overwrite File) : –  The > operator sends standard output (success stream – 1) to a specified file. If that file already exists, it will be overwritten. Example: Get-Process > processes.txt

This command saves the output of Get-Process to processes.txt, replacing any content that was previously there.

2. >> (Redirect Output – Append to File) : – The >> operator functions similarly to >, but instead of overwriting, it appends the output to the file.

Example: Get-Process >> processes.txt

This command adds the output to processes.txt without deleting any existing content.

3. >&1 (Merge Error Stream with Output Stream) : –  The >&1 operator combines error messages (2) with the success stream (1), allowing both types of output to be saved in the same file. Example: Get-Process invalidProcess > output.txt 2>&1 This command saves both the valid output and any errors to output.txt.

 

6. Split and Join Operators

PowerShell includes the split (-split) and join (-join) operators, which are useful for efficiently handling strings. These operators allow you to break a string into an array or merge an array back into a string.

 

1. Split Operator (-split)

The -split operator takes a string and divides it into an array based on a specified delimiter.

Example

$text = “Apple,Orange,Banana”

$fruits = $text -split “,”

$fruits

 

Output:

Apple

Orange

Banana

In this case, the string is split into an array using the comma as the delimiter.

 

Using Multiple Delimiters

You can also split a string using several separators by employing a regular expression. The | symbol acts as an “OR” operator in regex.

 

$text = “Apple|Orange,Banana;Grapes”

$fruits = $text -split “[,;|]”

$fruits

 

Output:

Apple

Orange

Banana

Grapes

Here, the string is split using |, ,, and ; as the delimiters.

 

Limiting the Number of Splits

You can specify a limit to control how many times the string is split.

 

$text = “One-Two-Three-Four-Five”

$words = $text -split “-“, 3

$words

 

Output:

One

Two

Three-Four-Five

In this example, the string is split only twice, with the remaining text kept in the last element.

 

2. Join Operator (-join)

The -join operator merges the elements of an array into a single string, using a specified separator.

 

Example

$fruits = @(“Apple”, “Orange”, “Banana”)

$text = $fruits -join “, “

$text

 

Output:

Apple, Orange, Banana

The elements of the array are combined into one string with “, ” as the separator.

 

Joining Without a Separator

If you don’t provide a separator, the elements will be concatenated without any spaces.

 

$letters = @(“P”, “o”, “w”, “e”, “r”)

$word = $letters -join “”

$word

 

Output:

Power

In this case, the array is combined into a single word.

 

3. Using Split and Join Together

 

You can split a string, make modifications, and then join it back together.

$text = “John|Doe|30|USA”
$words = $text -split “\|”
$words[2] = “31” # Modifying an element
$newText = $words -join “|”
$newText

Output:
John|Doe|31|USA

PowerShell Script which includes almost all Operators

# String Variables
$name = “John”
$surname = “Doe”
$fullName = $name + ” ” + $surname # String concatenation using +

# Integer Variables
$num1 = 10
$num2 = 5
$sum = $num1 + $num2 # Addition
$difference = $num1 – $num2 # Subtraction
$product = $num1 * $num2 # Multiplication
$quotient = $num1 / $num2 # Division
$remainder = $num1 % $num2 # Modulus (remainder)

# Floating-Point Variables
$float1 = 10.5
$float2 = 2.5
$floatSum = $float1 + $float2 # Addition with decimals

# Boolean Variables
$isAvailable = $true
$isComplete = $false
$check = $isAvailable -and $isComplete # Logical AND
$check2 = $isAvailable -or $isComplete # Logical OR

# Array Variables
$fruits = @(“Apple”, “Banana”, “Cherry”)
$fruits += “Mango” # Adding an element to an array
$firstFruit = $fruits[0] # Accessing first element
$fruitCount = $fruits.Length # Getting array length

# Hashtable Variables
$person = @{
“Name” = “John Doe”
“Age” = 30
“Country” = “USA”
}
$person[“City”] = “New York” # Adding a new key-value pair

# Comparison Operators
$isEqual = ($num1 -eq $num2) # Equals (False)
$isNotEqual = ($num1 -ne $num2) # Not Equals (True)
$isGreater = ($num1 -gt $num2) # Greater Than (True)
$isLess = ($num1 -lt $num2) # Less Than (False)

# Assignment Operators
$num1 += 5 # Equivalent to $num1 = $num1 + 5
$num2 *= 2 # Equivalent to $num2 = $num2 * 2

# Type Operators
$isString = $name -is [string] # Checking type (True)
$isInt = $num1 -is [int] # Checking type (True)

# Redirection Operators
“PowerShell Output” > “output.txt” # Writing output to a file
Get-Process | Out-File “processes.txt” # Redirecting command output

# Pipeline Operators
Get-Process | Where-Object {$_.CPU -gt 100} # Filtering processes with CPU > 100

# Join and Split Operators
$sentence = “Hello,World,PowerShell”
$words = $sentence -split “,” # Splitting string into array
$joinedWords = $words -join ” ” # Joining array into string

# Output results
Write-Output “Full Name: $fullName”
Write-Output “Sum: $sum, Difference: $difference, Product: $product, Quotient: $quotient”
Write-Output “Boolean Check (AND): $check, (OR): $check2”
Write-Output “First Fruit: $firstFruit, Fruit Count: $fruitCount”
Write-Output “Person Details: $person”
Write-Output “Comparison: Equal($isEqual), Not Equal($isNotEqual), Greater($isGreater)”
Write-Output “Number after assignment operations: $num1, $num2”

 

Output

Full Name: John Doe
Sum: 15, Difference: 5, Product: 50, Quotient: 2
Boolean Check (AND): False, (OR): True
First Fruit: Apple, Fruit Count: 4
Person Details: Name=John Doe Age=30 Country=USA City=New York
Comparison: Equal(False), Not Equal(True), Greater(True)
Number after assignment operations: 15, 10

Check out more Blogs – Click Here

Visit Our LinkedIn Page – Click Here