top of page
Search
• shishir kushawaha

# PowerShell Operators: Your Key to Efficient Scripting

PowerShell is a powerful scripting language that offers a wide range of operators to manipulate and process data efficiently. In this blog post, we will explore the essential operators in PowerShell and their usage. Whether you are a beginner or an experienced PowerShell user, understanding these operators is crucial for writing effective scripts and performing various operations. Let's dive in! Arithmetic Operators:

Arithmetic operators allow you to perform mathematical calculations in PowerShell. They include addition (+), subtraction (-), multiplication (*), division (/), and modulus (%).

- (Subtraction) Subtracts the right-hand operand from the left-hand operand.
* (Multiplication) Multiplies two values or shows the result of the left-hand operand as a multiple of the right-hand operand.
/ (Division) Divides the left-hand operand by the right-hand operand.
% (Modulus) Divides the left-hand operand by the right-hand operand and returns the remainder.

Let's see some examples to understand how these operators work:

```\$a = 20
\$b = 15
\$sum = \$a + \$b
\$diff = \$a - \$b
\$product = \$a * \$b
\$quotient = \$a / \$b
\$remainder = \$a % \$b
Write-Host "Sum: \$sum" # Result Sum: 35
Write-Host "Difference: \$diff" #Result Difference: 5
Write-Host "Product: \$product" #Reult Product: 300
Write-Host "Quotient: \$quotient" #Result Quotient: 1.33
Write-Host "Remainder: \$remainder" #Result Remainder: 5```

Strings, arrays, and hashtables can all be utilized using the plus (+) and asterisk (*) operators. The multiplication operator makes multiple copies of the input when used with strings, whereas the addition operator concatenates the input. It's interesting that several object types can be mixed in an arithmetic statement. The type of the expression's leftmost object governs how the statement is evaluated.

Find some more examples where mixed operands are used.

```"power" + "shell"            # result = powershell
5 + "Five"                  # Error as left operands data type governs the evaluation. 'Five' will be converted to Int32 which results in error.
5 + "5"                     # result = 10
"5" + "5"                   # result = 55
"Fifty" + 5                 # result = Fifty5
@(1, "one") + @(2.0, "two")  # result = @(1, "one", 2.0, "two")
@{"one" = 1} + @{"two" = 2}  # result = @{"one" = 1; "two" = 2}```

Assignment Operators:

Assignment operators are used to assign values to variables. PowerShell offers various assignment operators, such as the equal sign (=), plus-equal (+=), minus-equal (-=), multiply-equal (*=), divide-equal (/=), and modulus-equal (%=). Compound assignment operators refer to the integration of arithmetic operators with the assignment operator (=). These operators allow performing arithmetic operations on values before assigning them to a variable.

= (Simple assignment operator): It assigns the value of the right-side operand to the left-side operand.
+= (Add AND assignment operator): It adds the right operand to the left operand and assigns the result to the left operand.
-= (Subtract AND assignment operator): It subtracts the right operand from the left operand and assigns the result to the left operand.
*= (Multiply AND assignment operator): It multiplies the left operand by the right operand and assigns the result to the left operand.
/= (Divide AND assignment operator): It divides the left operand by the right operand and assigns the result to the left operand.
%= (Modulus AND assignment operator): It divides the left operand by the right operand, calculates the remainder, and assigns the result to the left operand.

Let's see how these operators work:

```\$a = 10
\$a += 5
Write-Host "After addition: \$a" # Value of variable a is 15
\$a -= 3
Write-Host "After subtraction: \$a" # Value of variable a is 12
\$a *= 2
Write-Host "After multiplication: \$a" # Value of variable a is 24
\$a /= 4
Write-Host "After division: \$a" # Value of variable a is 6
\$a %= 3
Write-Host "After modulus: \$a" # Value of variable a is 0```

Comparison Operators:

Comparison operators enable you to compare values or expressions in PowerShell. They include equal to (-eq), not equal to (-ne), less than (-lt), less than or equal to (-le), greater than (-gt), and greater than or equal to (-ge).

-eq (equals): Compares two operands to check if they are equal.
-ne (not equals): Compares two operands to check if they are not equal.
-gt (greater than): Checks if the first operand is greater than the second operand.
-ge (greater than or equals to): Checks if the first operand is greater than or equal to the second operand.
-lt (less than): Checks if the first operand is less than the second operand.
-le (less than or equals to): Checks if the first operand is less than or equal to the second operand.

Let's explore some examples:

```\$a = 10
\$b = 5

if (\$a -eq \$b) {Write-Host "Equal"}
if (\$a -ne \$b) {Write-Host "Not equal"}
if (\$a -lt \$b) {Write-Host "\$a is less than \$b"}
if (\$a -gt \$b) {Write-Host "\$a is greater than \$b"}
if (\$a -le \$b) {Write-Host "\$a is less than or equal to \$b"}
if (\$a -ge \$b) {Write-Host "\$a is greater than or equal to \$b"}```

Logical Operators:

Logical operators allow you to combine or invert conditions in PowerShell. They include logical AND (-and), logical OR (-or), logical XOR (-xor), and logical NOT (-not, !).

-and (logical and): The Logical AND operator checks if both operands/statements are true. If both are true, the condition becomes true.
-or (logical or): The Logical OR operator checks if either of the two statements evaluated to true. If at least one operand is true, the condition becomes true.
-not (logical not): The Logical NOT operator reverses the logical state of its statement/operand. If a condition is true, the Logical NOT operator makes it false.
-xor (logical exclusive or): The Logical Exclusive OR operator checks if the statements have different truth values. If exactly one operand is true, the condition becomes true.

Let's see some examples:

```\$a = \$true
\$b = \$false

if (\$a -and \$b) {Write-Host "Both conditions are true"}
if (\$a -or \$b) {Write-Host "At least one condition is true"}
if (\$a -xor \$b) {Write-Host "Only one condition is true"}
if (-not \$a) {Write-Host "Negation of \$a"}```

Redirectional Operators:

Redirectional operators are used to redirect input and output in PowerShell. The greater than sign (>) is used for output redirection, while the double greater than sign (>>) appends output to a file. Let's see some examples:

```# Output redirection
Get-Process > processes.txt
# Append output to a file
Get-Service >> services.txt```

Unary Operators:

Unary operators operate on a single operand and perform various actions. The unary increment operator (++) and decrement operator (--) are commonly used in PowerShell. Let's see some examples:

```\$a = 5
\$a++
Write-Host "After increment: \$a"
\$a--
Write-Host "After decrement: \$a"```

Type Operators:

Type operators help you determine the type of an object in PowerShell. They include -is, -isnot, and -as. Let's explore some examples:

```\$a = 10
if (\$a -is [int]) {Write-Host "\$a is an integer"}
if (\$a -isnot [string]) {Write-Host "\$a is not a string"}

\$b = "Hello"
\$c = \$b -as [int]
Write-Host "Converted value: \$c"```

Brackets in PowerShell:

PowerShell uses different types of brackets, such as {}, (), [], for various purposes. Let's explore their usage:

Square Brackets []: Square brackets are used for accessing elements in arrays, indexing elements in strings, and filtering elements in hash tables. It can also be used for setting data type explicitly.

• Index operator []:

```# Accessing elements in an array
\$myArray = @(1, 2, 3)
\$element = \$myArray  # Retrieves the value 2

# Indexing elements in a string
\$myString = "Hello"
\$character = \$myString  # Retrieves the character "H"

# Filtering elements in a hash table
\$myHashTable = @{ "Name" = "John"; "Age" = 30 }
\$name = \$myHashTable["Name"]  # Retrieves the value "John"```
• Cast operator[]:

```\$number = [int]"10"
Write-Host "Number: \$number"```

Curly braces {} : In PowerShell, curly braces {} have several important uses. It can be used while defining the hashtable, functions, scriptblock etc.

• Define Hashtable

```\$person = @{
Name = "John"
Age = 25
}
Write-Host "Person Name: \$(\$person.Name)"
Write-Host "Person Age: \$(\$person.Age)"```

Parentheses (): Parentheses are primarily used for grouping expressions and determining the order of evaluation. They are also used when calling functions or cmdlets, passing arguments, and evaluating expressions. It is also used to define array.

• Array subexpression operator ():

```\$numbers = (1, 2, 3)
\$total = (\$numbers + \$numbers) * \$numbers
Write-Host "Total: \$total"```
• Subexpression \$():

```\$a = 5
\$b = 10
\$message = "The sum of \$a and \$b is \$(\$a + \$b)"
Write-Host \$message```

Call Operator (&) or Invoke-Expression:

The call operator (&) is used to invoke a command, function, script or a script block.

Example:

```\$command = "& 'C:\Scripts\MyScript.ps1'"
Invoke-Expression \$command```

In this example, the call operator is used to execute the script MyScript.ps1.

```function MyFunction {
param(
[string]\$Name
)
Write-Host "Hello, \$Name!"
}

& MyFunction -Name "John"```

Above example demonstrate calling function by call operator.

```\$myScriptBlock = {
Get-ChildItem -Path C:\Windows
}
& \$myScriptBlock```

Here & operator is used to execute the scriptblock.

Comma Operator (,) and Dot Sourcing Operator (.) or Member Access Operator:

The comma operator (,) is used to create an array, and the dot sourcing operator (.) or member access operator is used to access properties or methods of an object.

Example:

```\$numbers = 1, 2, 3
\$length = \$numbers.Count
\$person = [PSCustomObject]@{
Name = "John"
Age = 25
}
\$person.Name```

In this example, the comma operator is used to create an array of numbers. The dot sourcing operator is used to access the Count property of the \$numbers array, and the member access operator is used to access the Name property of the \$person object.

Pipeline Operator (|):

The pipeline operator (|) is used to pass the output of one command as the input to another command.

Example:

`Get-Process | Where-Object {\$_.WorkingSet -gt 1GB} | Sort-Object -Property CPU`

Processing of above command through pipeline:

1. Get-Process: This cmdlet retrieves information about all currently running processes on the system. It returns a collection of process objects.

2. |: The pipeline operator (|) takes the output (process objects) from the previous cmdlet (Get-Process) and passes it as input to the next cmdlet.

3. Where-Object {\$_.WorkingSet -gt 1GB}: The Where-Object cmdlet filters the collection of process objects received from the previous cmdlet. It selects only those process objects where the "WorkingSet" property is greater than 1GB. The \$_ represents the current object being processed in the pipeline.

4. |: Again, the pipeline operator (|) takes the filtered output (process objects where WorkingSet > 1GB) from the previous cmdlet (Where-Object) and passes it as input to the next cmdlet.

5. Sort-Object -Property CPU: The Sort-Object cmdlet sorts the collection of process objects based on the "CPU" property, which represents the percentage of CPU usage for each process. The -Property parameter specifies that we want to sort based on the "CPU" property.

Range Operator (..):

The range operator (..) is used to create a range of values.

Example:

```\$numbers = 1..10
Write-Host \$numbers```

In this example, the range operator is used to create an array of numbers from 1 to 10.

ForEach-Object (%):

The ForEach-Object (%) operator is used to iterate over a collection and perform an action on each item.

Example:

```\$fruits = "Apple", "Banana", "Orange"
\$fruits | ForEach-Object {
Write-Host "I love \$_"
}```

In this example, the ForEach-Object operator is used to iterate over the \$fruits array and output a message for each fruit.

Where-Object (?):

The Where-Object (?) operator is used to filter objects based on specified criteria.

Example:

```\$numbers = 1..10
\$evenNumbers = \$numbers | Where-Object {\$_ % 2 -eq 0}
Write-Host \$evenNumbers```

In this example, the Where-Object operator is used to filter the \$numbers array and retrieve only the even numbers between 1 to 10.

Collection Membership Operators (-in, -notin, -contains, -notcontains):

The in and notin operators (-in, -notin) check if a value is a member or not a member of a collection. The contains and notcontains operators (-contains, -notcontains) perform the same check on a specific property of an object.

Example:

```\$fruits = "apple", "banana", "orange"
if ("apple" -in \$fruits) {Write-Host "Apple is in the list"}
if (\$fruits -contains "pear") {Write-Host "The list contains pear"}```

Output: "Apple is in the list"

Mastering operators is crucial for PowerShell scripting proficiency. This blog post covers an extensive array of operators, encompassing arithmetic, assignment, comparison, logical, redirection, unary, and type operators. Gaining familiarity with these operators empowers you to perform complex operations efficiently, enhancing your PowerShell scripting skills significantly. Engage in hands-on experimentation with these operators to explore their diverse applications and unlock your potential as a proficient PowerShell user.