Understanding how operators work will lead to more efficient code.
PowerShell is intended to be an interactive command-line, but it’s also a programming language. As we advance into PowerShell knowledge, it’s inevitable for us to learn many of core computer programming concepts. The operator is one of those important programming concepts that you probably have been using but without having comprehensive knowledge about them.
The operator belongs to one or more characters in an expression or command that PowerShell interprets in a specific way. While creating a module or script, we’ll use PowerShell operators and those are categorized into several types. For instance, operators for performing arithmetic, operators for comparing values, operators for manipulating strings, and more.
Get in-depth knowledge of task automation and configuration management with our PowerShell Training
PowerShell Operators
Arithmetic operators are used in mathematical expressions as used in algebra. These operators also include the modulus (%) operator to calculate the remainder of the division operation. This means we can use PowerShell just by typing expressions at the PowerShell prompt.
We can use PowerShell as a simple calculator by just typing expressions at the PowerShell prompt. The arithmetic expressions in PowerShell are evaluated from left to right as per the order of operations unless we use parentheses for grouping (multiplication, division, addition, then subtraction). The spaces between the operators are ignored in PowerShell to make things clearer.
The + and * operators can also be used to work with strings. When you use the * operator, it repeats a string. When you use the + operator, it concatenates strings.
Assume integer variable A holds 30 and variable B holds 10, then −
Operator | Description | Example |
+ (Addition) | This operator is used for adding values on either side of the operator. | A + B will give 40 |
- (Subtraction) | This operator is used for subtracting right-hand operand from the left-hand operand. | A - B will give -20 |
* (Multiplication) | This operator is used for multiplying values on either side of the operator. | A * B will give 300 |
/ (Division) | This operator is used for dividing left-hand operand by right-hand operand. | B / A will give 3 |
% (Modulus) | This operator is used for dividing left-hand operand by right-hand operand and returns the remainder. | B % A will give 0 |
In PowerShell, the assignment operators are used to assign, change, or append the values in a variable. (=) is the most commonly used assignment operator, which is used for assigning a given value to the variable.
Operator | Description | Example |
= | This is a simple assignment operator which assigns values from right side operands to left side operands. | Z= X+ Y will assign the value of X + Y into Z |
- = | The Subtract AND operator is used to subtract right operand from the left operand and assigns the result to left operand. |
Z-= X is similar to Z= Z- X |
+ = | The Add AND operator is used to add the right operand to the left operand and assigns the result to the left operand. | Z+= X is similar to Z= Z+ X |
There are some other assignment operators (*=, %=, /=,), which are used for modifying the value of a variable.
Related Article: PowerShell Tutorial
In PowerShell, the logical operators are used to connect statements or expressions collectively to form a single expression. The expressions which contain the logical operators usually result in the Boolean values $True or $False.
The logical operators connect conditional statements into a single complex conditional. Assume Boolean variables X holds true and variable Y holds false, then −
Operator | Description | Example |
AND (logical and) | Referred to as Logical AND operator. The condition is true if both the operands are non-zero. | (X -AND Y) is false |
OR (logical or) | Referred to as Logical OR Operator. The condition is true If any of the two operands are non-zero. | (X -OR Y) is true |
NOT (logical not) | Referred to as Logical NOT Operator. For reversing the logical state of the operand, it is used. If a condition is true then it returns false. |
-NOT(X -AND Y) is true
|
The PowerShell stops evaluating expressions on either side of a logical operator once it returns a $true result, and this is called short-circuit evaluation.
The comparison operators are used in PowerShell to compare the values for equality, matching, containment, and replacement. These operators are prefixed with a hyphen (-) such as -eq like the majority of other operators, to verify whether two values are equal.
PowerShell includes the following comparison operators:
4.1. Equality Operator
Type | Operator | Description |
Equality | -eq | Compares two values to be equal or not. |
-ne | Compare the two values to be not equal. | |
-gt | Compares the first value to be greater than the second one. | |
-ge | Compare the first value to be greater than or equals to the second one. | |
-lt | Compare the first value to be less than the second one. | |
-le | Compares first value to be less than or equals to second one. |
All the equality operators return a boolean value ($true or $false). The operators return a value of TRUE or matches when input values identical to the specified pattern. The entire pattern must match an entire value.
-eq: Equal to. Includes an identical value.
Example:
PS> 4 -eq 4
Output: TruePS> 4 -eq 3
Output: FalsePS> "xyz" -eq "xyz"
Output: TruePS> "xyz" -eq "xyz", "def"
Output: False-ne: Not equal to. Includes a different value.
Example:
PS> "xys" -ne "ghu"
Output: TruePS> "xys" -ne "xys"
Output: FalsePS> "xys" -ne "xys", "def"
Output: True-gt: Greater-than.
Example:
PS> 8 -gt 6
Output: TruePS> 7, 8, 9 -gt 8
Output: 9-ge: Greater-than or equal to.
Example:
PS> 8 -ge 8
Output: TruePS> 7, 8, 9 -ge 8
Output:8
9
-lt: Less-than.
Example:
PS> 8 -lt 6
Output: FalsePS> 7, 8, 9 -lt 8
Output: 7-le: Less-than or equal to.
Example:
PS> 6 -le 8
Output: True7
The match operators are “-like”, “-notlike”, “-match”, and “-notmatch”.
Operator
| Description | Example |
-like
|
This operator will return a true value when the string matches the wildcard pattern
|
PS> "PowerShell" -like "*shell" True
|
-notlike | This operator will return a true value when the string does not match the wildcard pattern |
PS> "PowerShell" -notlike "*shell" False
|
-match | This operator will return a true value when the string matches the regex pattern |
PS> "Good Dog" -match "Dog" True
|
-notmatch |
This operator will return a true value when the string does not match regex pattern
|
PS> "Sunday" -notmatch "sun" False
|
The operators like “-like” and “-notlike” use wildcard characters to find the elements that match or don’t match a specified pattern.
The syntax is:
<string[]> -like <wildcard-expression>
<string[]> -notlike <wildcard-expression>
Whereas “-match” and “-notmatch” operators use regular expressions to find elements that match or do not match a specified pattern .
The syntax is:
<string[]> -match <regular-expression>
<string[]> -notmatch <regular-expression>?
There are two containment operators in PowerShell such as “-contains” and “-notcontains”, which are similar to equality operators. They always return a boolean value depending on whether the value on the right side of the operator exists in the set of values on the left side of the operator (true or false).
-contains
This operator tells whether a set of reference values includes a single test value
Syntax:
<Reference-values> -contains <Test-value>
Returns true only when the test value exactly matches the at least one of the reference values.
Example:
PS> "xyz", "abc" -contains "abc"
Output: TruePS> "Linux", "Windows" -contains "Drive"
Output: False #Not an exact match-notcontains
This operator tells whether a collection of reference values includes a single test value. Also, returns TRUE when the test value is not an exact match for at least one of the reference values.
Syntax:
<Reference-values> -notcontains <Test-value>
Example:
PS> "Linux", "Windows" -notcontains "Drive"
Output: True #Not an exact match.-in
The -in operator was introduced in PowerShell 3.0. This operator tells whether a test value appears in a collection of reference values. Returns TRUE only when the test value exactly matches at least one of the reference values.
Syntax:
<Test-value> -in <Reference-values>
Example:
PS> "xyz" -in "dfg", "xyz"
Output: TruePS> "Drive" -in "Windows", "Linux"
Output: False #Not an exact matchPS> "Drive" -in "Drive", "Windows"
Output: True #An exact match-notin
The “-notin” operator was introduced in PowerShell 3.0. This operator tells whether a test value appears in a collection of reference values. Returns TRUE when the test value is not an exact match for at least one of the reference values
Syntax:
<Test-value> -notin <Reference-values>
Example: PS> "xyz" -notin "dfg", "xyz"
Output: FalsePS> "abc" -notin "hjk", "oip"
Output: TrueThis operator replaces part of the value or all the value with the specified value using regular expressions. It uses two arguments for a regular expression pattern and replacement value, and those are separated by a comma.
Let’s take a look into PowerShell Interview Questions
The syntax of the -replace operator is as follows, the <original> placeholder describes the characters to be replaced, whereas the <substitute> placeholder describes the characters that replaces them:
<input> <operator> <original>, <substitute>
By default, the -replace operator is case-insensitive. We can use -creplace to make it case sensitive. Use -ireplace, to make it explicitly case-insensitive.
Example:
PS> "Maddy" -replace "M", "D"
Output: Daddy"maddy" -ireplace "M", "D"
Output: Daddy"maddy" -creplace "M", "D"
Output: maddyRelated Article: PowerShell Interview Questions
To determine whether an object belongs to a specific type, type comparison operators are used in PowerShell. There are two type comparison operators such as “-is” and “-isnot”.
-is
Syntax:
<object> -is <type reference>
Example:
PS> $a = 5
PS> $b = "5"
PS> $a -is [int]
True
PS> $a -is $b.GetType()
False?
-isnot
Syntax:
<object> -isnot <type reference>
Example:
PS> $a = 5
PS> $b = "5"
PS> $a -isnot $b.GetType()
True
PS> $b -isnot [int]
True?
To divide and combine substrings, split and join operators are used. The -split operator is used to split a string into substring, whereas the -join operator is used to concatenate various strings to a single string. Both these operators are widely used in PowerShell scripts for manipulating strings. It allows you to specify one or more delimiter characters for how the PowerShell should split or join strings.
Redirection operators are very important to use in PowerShell, as of now it supports output redirection, but might support input redirection in future versions. The redirection operators supported from PowerShell 3.0 are listed below:
Description |
This operator is used to redirect the standard (non-error) output to a file |
This operator is used to redirect the output and appends it to a file |
This operator is used to redirect error output to a file |
This operator is used to redirect the error output and append it to a file |
This operator is used to redirect the error output to the same location as standard output |
This operator is used to redirect the warning output to a file |
This operator is used to redirect the warning output and append it to a file |
This operator is used to redirect verbose output to a file |
This operator is used to redirect the verbose output and append it to a file |
This operator is used to redirect the debug output to a file |
This operator is used to redirect the debug output and appends it to a file |
This operator is used to redirect the warning (n = 3), verbose (n = 4), or debug (n = 5) output to the same location as standard output |
This operator is used to redirect all output streams (standard, error warning, verbose, and debug) to a file |
This operator is used to redirect all output streams and appends them to a file |
Related Article: Explore the list of basic PowerShell commands
To increment or decrement variables or set integers to a positive or negative value, we use unary operators in PowerShell.
For example, to increment the variable $a from 20 to 21, we type $a++.
PowerShell special operators have specific use-cases that don’t fall into any other operator groups. The functioning of these special operators includes changing a value’s data type, running commands or retrieving elements from an array.
Let’s take a look at different special operators used in PowerShell.
The invocation (&) operator
This operator is used to run a script, command, or script block. The & operator is used to run a program that contains spaces in its path or name.
For instance, for the following command
"D:Program Files (x86)Test AppMyApp.exe"
It just displays a string on screen but doesn’t start the program MyApp.exe. To run MyApp.exe as a program, just place the & operator before the string:
& "D:Program Files (x86)Test AppMyApp.exe"
Subexpression operator $( )
This is used to evaluate the expression in between the $( and the ) characters. This operator is used to return one or more statements. It returns scalar for a single statement and returns an array for multiple statements. For using an expression within another expression, we use this operator.
Example: To embed the results of a command in a string expression
PS> "Today is $(Get-Date)"
Today is 26/06/2020 13:15:20PS> "Folder list: $((dir c: -dir).Name -join ', ')"
Folder list: Program Files, Program Files (x86), Users, WindowsArray subexpression operator @( )
This operator returns the result of one or more statements as an array. If there is only one item, the array has only one member.
@(Get-CimInstance win32_logicalDisk)
The static member (::) operator.
For accessing a static member of a .NET class, we use the static member operator
A class is a type of object, and a static member is a property or method of a class. For example, the expression
[DateTime]::Now
refers to the Now static property of the DateTime .NET class.The range operator (..)
Returns an array of integers represented by the upper and lower bounds of integers on either side of the two consecutive dots.
For example, expression 3..6 outputs a four-element array (3,4,5,6) and expression 6..4 outputs a three-element array (6,5,4).
The comma (,) operator.
The comma operator (,) will create an array as a binary operator and creates an array with one member as a unary operator. If you place the comma operator before a single value, you can create a one-element array.
For example, the expression
$items = ,"B"
Assigns a one-element array to the variable $items.
You can also place the comma operator between items in a list to create a multiple-element array. For example, the expression
$items = "X","Y","Z"
assigns a three-element array to the variable $items.Format operator -f
Formats a string based on .NET string formatting rules. On the left side of the operator enter the format string and on the right side of the operator enter the objects to be formatted.
For example,
"{0} {1,-10} {2:N}" -f 1,"hello",[math]::pi
Output:
1 hello 3.14
The dot sourcing (.) operator
This operator is used to run a script in the current scope and is followed by space. The PowerShell creates a new scope for the script you run that functions and variables, the script creates are discarded when the script terminates.
While running a script, if you don’t want PowerShell to create a new scope, then prefix the script with the dot sourcing operator.
For example, If we have a list of useful functions in the script file Sample.ps1. Use the dot sourcing operator to load the scripts:
. Sample.ps1
The functions defined in Sample.ps1 will now be available after the script terminates.
Null-coalescing assignment operator ??=
If the left-hand operand evaluates to null, then the operator assigns the value of its right-hand operand to its left-hand operand only. If the left-hand operand evaluates to non-null, then the operator doesn't evaluate its right-hand operand.
For example,
$x = $null
$x ??= 200
$x?
Output:
200
In the following example, the right-hand operand won't be evaluated.
[string] $todaysDate = '27/06/2020'
$todaysDate ??= (Get-Date).ToShortDateString()?
Output:
27/06/2020
Null-coalescing operator ??
Thi operator returns the value of its left-hand operand if it isn't null. Otherwise, evaluates the right-hand operand and returns its result. If the left-hand operand evaluates to non-full, this operator doesn’t evaluate its right-hand operand.
For example:
$x = $null
$x ?? 200?
Output: 200
In the following example, the right-hand operand won't be evaluated.
[string] $todaysDate = '27/06/2020'
$todaysDate ?? (Get-Date).ToShortDateString()?
Output: 27/06/2020
In this blog, we have covered a variety of operators in PowerShell. It’s always helpful for you to know in advance what type of operator you are working in PowerShell to improve the efficiency of your code.
Also, if you are looking for a structured learning approach towards PowerShell, then enroll in our PowerShell Course that kick starts your PowerShell career.
PS> 7, 8, 9 -le 8
Our work-support plans provide precise options as per your project tasks. Whether you are a newbie or an experienced professional seeking assistance in completing project tasks, we are here with the following plans to meet your custom needs:
Name | Dates | |
---|---|---|
PowerShell Training | Nov 16 to Dec 01 | View Details |
PowerShell Training | Nov 19 to Dec 04 | View Details |
PowerShell Training | Nov 23 to Dec 08 | View Details |
PowerShell Training | Nov 26 to Dec 11 | View Details |
Madhuri is a Senior Content Creator at MindMajix. She has written about a range of different topics on various technologies, which include, Splunk, Tensorflow, Selenium, and CEH. She spends most of her time researching on technology, and startups. Connect with her via LinkedIn and Twitter .