PowerShell Operators [Complete Guide]

When using PowerShell you can use a wide variety of operators in your script. They can be used in commands or expressions and are used to perform comparisons, define conditions, or assign and manipulate values.

If you are using PowerShell 7, then you can also use the new Ternary operators. These allow you to create online if-else statements, making your code more readable.

In this article

In this article, we are going to take a look at the different operators. I have divided them into groups, so you can easily reference them.

Assignment Operators

The most commonly used operators are the assignment operators. These operators are used to assign, manipulate, or append values to variables.

OperatorExampleDescription
=$a = 5Assigns the value on the right to the left.
+=$a += 3Adds the right operand to the left and assigns it.
-=$a -= 2Subtracts the right operand from the left and assigns it.
*=$a *= 4Multiplies the left operand by the right and assigns it.
/=$a /= 2Divides the left operand by the right and assigns it.

For example, we can assign the value 10 to the variable $count and add 5 to it, making the total 15:

Comparison Operators

Comparison operators in PowerShell can be divided into 4 groups. We have operators to compare values, for example, to test if $a is greater than $b with ($a -gt $b) , operators to find and even replace patterns, to test is a value appears in a set and to check if an object is a specific type.

The basic comparison operators in PowerShell are:

OperatorExampleDescription
-eq5 -eq $aReturns if both operands are equal.
-ne5 -ne $aReturns if operands are not equal.
-gt$a -gt 5Returns if the left operand is greater.
-lt$a -lt 5Returns if the left operand is less.
-ge5 -ge $aReturns if the left operand is greater or equal.
-le5 -le $aReturns if the left operand is less or equal.

As you can see in the table above, the variable is on the right side when using the equality operators. The reason for this is when you use the -eq operator between an array and a scalar value (like a number), then PowerShell doesn’t return True or False .

Instead, it will compare the scalar value with each element in the array. If the scalar value exists in the array, then it will return the array element instead of True.

We also have comparison operators that we can use to find or even replace patterns in strings. The -match and -replace operators use regex for the comparison whereas the -like operator uses a wildcard.

OperatorExampleDescription
-match$string -match “foo”Returns if the string matches the regex pattern.
-notmatch$string -notmatch “foo”Returns if the string does not match the regex pattern.
-replace$string -replace “foo”, “bar”Replaces text that matches a regex pattern.
-like$string -like “foo*”Returns if the string matches the wildcard pattern.
-notlike$string -notlike “foo*”Returns if the string does not match the wildcard pattern.

The containment comparison operators are used to check if a value is present or not in a reference set, like an array for example. Both operators, -contains and -in , can be used to check if an item is present in a collection.

The only difference between the two is the place of the value and collection. Which one you should use really depends on the context.

OperatorExampleDescription
-contains$array -contains 5Returns if the array contains the specified value.
-notcontains$array -notcontains 5Returns if the array does not contain the value.
-in5 -in $arrayReturns if the left operand is in the array.
-notin5 -notin $arrayReturns if the left operand is not in the array.

The last comparison operators that we can use in PowerShell are the -is operators. This one isn’t used a lot but allows you to check if an object is of the specified type or not.

OperatorExampleDescription
-is$object -is [Type]Returns if the object is of the specified type.
-isnot$object -isnot [Type]Returns if the object is not of the specified type.

Logical Operators

Logical Operators are used to connect conditional statements in PowerShell to a single statement.

OperatorExampleDescription
-and(5 -gt 3) -and (6 -gt 2)Returns if both conditions are true.
-or(5 -gt 7) -or (8 -gt 2)Returns if any of the conditions are true.
-not-not (5 -eq 5)Reverses the logic of its operand.
!!(3 -eq 4)Short form of .

For example, we can use the -and operator to check if a value is less than 10 and greater than 2 with the command below:

Redirection Operators

The redirection operators in PowerShell share some similarities with the ones from Command Prompt. But PowerShell also has some of its own.

You can use the redirection operators to send the output of a command to a text file. The different options not only allow you to send or append the normal (standard) output to a file. It’s also possible to redirect only the error stream or warning stream. Which is great when you want to create an error log for your script.

OperatorExampleDescription
>Get-Process > processes.txtRedirects standard output to a file.
>>Get-Process >> log.txtAppends standard output to a file.
2>Get-Command xyz 2> errors.txtRedirects error output to a file.
2>>Get-Command xyz 2>> errors.logAppends error output to a file.
2>&1Get-Process 2>&1 alloutput.txtRedirects error stream to the succes stream
*>Get-Process *> alloutput.txtRedirects all streams to a file

For example, to write only the errors of a command to a file we can use the redirect stream operator:

Split and Join Operators

The split and join operators are used to split or join strings .

OperatorExampleDescription
-split‘one,two,three’ -split ‘,’Splits a string into an array based on a delimiter.
-join(‘one’,’two’) -join ‘,’Joins array elements into a single string.

Type Operators

We have seen the type operator -is also in the comparison operator section. The operator is used to check if a variable is of a specific type. But besides the -is operator, we can also use the -as operator to convert a variable into a specific type.

OperatorExampleDescription
-is$var -is [int]Checks if a variable is of a specified type.
-as$var -as [string]Tries to convert a variable to a specified type.
[Type][int]$varCasts a variable to a specified type.

The -as operator is particularly handy when you need to convert a string into an integer for example

Unary Operators

Unary operators are used quite a lot, especially in loops, to either keep track of the index or for counting. Fun fact, the ++ operator is probably the most used, but most don’t know that it’s called a Unary operator.

OperatorExampleDescription
-$varNegates the value of the operand.
++++$varIncrements the operand’s value by 1.
–$varDecrements the operand’s value by 1.

Special Operators

These operators don’t really fit into the other groups, because each has there own special use case

OperatorExampleDescription
&& script.ps1Executes a script or command.
.. script.ps1Executes a script in the current scope.
()($a + $b) * $cEnsure that expressions are evaluated in a specific order
$( )$(Get-Date)Subexpression operator; runs the command in a subexpression.
`“This is a backtick `n”Escape character; used to include special characters in strings.
..$a = 1..10Create an array with a range of integer from 1 to 10.

The grouping operators, better known as parentheses, are used to ensure that expressions or cmdlets are executed in a specific order. In the example below, we want the get the item path first, and then check if the length is greater than 100.

Ternary Operator Table

The ternary operator was released in PowerShell 7. It simplifies the if-else statements , making them easier to read. I do recommend only using the ternary operator for short if-else statements that fit on a single line.

OperatorExampleDescription
? :$result = ($x -gt 10) ? ‘High’ : ‘Low’Returns High if $x is greater than 10,
otherwise returns Low.

In the example below we check if the variable $x is greater than 10, if that is the case, we set the status to high, otherwise to low:

Null-coalescing Operators

The null-coalescing operator ?? in PowerShell 7 allows you to quickly check if the given variable is null and set a default value instead.

If the value on the left side of the operator equals null, then the value on the right side (which can also be variable) is returned. You can also combine multiple null-coalescing operators to find the first non-null value.

OperatorExampleDescription
??$result = $value ?? DefaultValueReturns if it is not null; otherwise, returns .
??=$value ??= DefaultValueAssigns to if is null.
?.$result = $object?.PropertyAccesses of only if is not null.
?[]$element = $array?[index]Accesses the element at in only if is not null.

One of the nice things about the Null-coalescing Operators is that it allows you to, for example, only access a property of an object if that object is not null:

Wrapping Up

There are a lot of operators in PowerShell that we can use. Most are quite common and are also used in other programming languages. But if you are relatively new to scripting or programming, then make sure that you pay extra attention to the null-coalescing and ternary operators for PowerShell 7.

Hope you found this list useful, make sure that you subscribe to the newsletter or follow me on Facebook so you don’t miss the latest articles.

You may also like the following articles

assignment operators powershell

Steps to Install Exchange Online PowerShell Module

PowerShell Do-While

PowerShell Do While Loop Explained

assignment operators powershell

How to Get the Computer Name with PowerShell

Leave a comment cancel reply.

Notify me of followup comments via e-mail. You can also subscribe without commenting.

assignment operators powershell

So, about that AdBlocker... Will you consider disabling it?

Yes, ads can be annoying. But they allow me to keep writing content like this. You can also support me by Buying Me a Coffee ☕ or visit the shop to get some Tech-Inspired merchandise | Read more about disabling AdBlockers

Prince25's avatar

Operators are used to perform specific mathematical or logical functions on data, often stored in variables. PowerShell offers multiple types of operators to manipulate data including:

Arithmetic Operators

Assignment operators, unary operators, equality comparison operators, logical operators.

PowerShell arithmetic operators are used to calculate numeric values. These include:

Operator Name Description
Addition Adds numbers, concatenates strings and arrays.
Subtraction Subtracts or negates numbers.
Multiplication Multiplies numbers or copies strings and arrays a specified number of times.
Division Divides numbers.
Modulo Returns the remainder of a division operation.

Arithmetic operators are binary operators, which means they act on two operands. Their syntax in PowerShell is <Operand_1> <Arithmetic Operator> <Operand_2> .

Arithmetic operators, + and * , also work on strings and arrays.

Assignment operators can be used to assign, change, or append values to variables. These operators are a shorter syntax for assigning the result of an arithmetic operator. The general syntax of the assignment operators is: <Variable> <Assignment Operator> <Value> .

Operator Name Description
Assignment assigns value to variable .
Addition Compound Assignment is short for .
Subtraction Compound Assignment is short for .
Multiplication Compound Assignment is short for .
Division Compound Assignment is short for .
Modulo Compound Assignment is short for .

Unary operators increase or decrease the value of a variable by 1.

Operator Name Description
Increment is short for .
Decrement is short for .

Equality operators in PowerShell are binary operators that compare two integer or string values that return True if the operator condition is met, otherwise False .

Operator Name Description
Equal is if and are equal.
Not Equal is if and are not equal.
Greater Than is if is greater than .
Less Than is if is less than .
Greater Than or Equal to is if is greater than or equal to .
Less Than or Equal to is if is less than or equal to .

Logical operators allow us to combine multiple operator expressions and statements into complex conditionals. They operate on boolean values and return boolean values.

Operator Name Description
And is only if and are both .
Or is if either or is .
Xor is if only, but not both, or is .
or Not is when is and when is .

Operator Precedence

Precedence order is the order in which PowerShell evaluates the operators if multiple operators are used in the same expression. Operator precedence in PowerShell is as follows:

  • Parentheses: ( )
  • Unary operators: ++ , --
  • Arithmetic operators: * , / , % , + , -
  • Comparison operators: -eq , -ne , -gt , -ge , -lt , -le
  • -and , -or , -xor
  • Assignment operators: = , += , -= , *= , /= , %=

All contributors

Anonymous contributor's avatar

Looking to contribute?

  • Learn more about how to get involved.
  • Edit this page on GitHub to fix an error or make an improvement.
  • Submit feedback to let us know how we can improve Docs.

Learn PowerShell on Codecademy

Computer science, learn powershell.

  • Getting started with PowerShell
  • Awesome Book
  • Awesome Community
  • Awesome Course
  • Awesome Tutorial
  • Awesome YouTube
  • ActiveDirectory module
  • Amazon Web Services (AWS) Rekognition
  • Amazon Web Services (AWS) Simple Storage Service (S3)
  • Anonymize IP (v4 and v6) in text file with Powershell
  • Archive Module
  • Automatic Variables
  • Automatic Variables - part 2
  • Basic Set Operations
  • Built-in variables
  • Calculated Properties
  • Cmdlet Naming
  • Comment-based help
  • Common parameters
  • Communicating with RESTful APIs
  • Conditional logic
  • Creating DSC Class-Based Resources
  • CSV parsing
  • Desired State Configuration
  • Embedding Managed Code (C# | VB)
  • Enforcing script prerequisites
  • Environment Variables
  • Error handling
  • GUI in Powershell
  • Handling Secrets and Credentials
  • How to download latest artifact from Artifactory using Powershell script (v2.0 or below)?
  • Infrastructure Automation
  • Introduction to Pester
  • Introduction to Psake
  • Modules, Scripts and Functions
  • Naming Conventions
  • Arithmetic Operators
  • Assignment Operators
  • Comparison Operators
  • Logical Operators
  • Mixing operand types : the type of the left operand dictates the behavior.
  • Redirection Operators
  • String Manipulation Operators
  • Package management
  • Parameter sets
  • PowerShell "Streams"; Debug, Verbose, Warning, Error, Output and Information
  • PowerShell Background Jobs
  • PowerShell Classes
  • PowerShell Dynamic Parameters
  • PowerShell Functions
  • Powershell Modules
  • Powershell profiles
  • Powershell Remoting
  • powershell sql queries
  • PowerShell Workflows
  • PowerShell.exe Command-Line
  • PSScriptAnalyzer - PowerShell Script Analyzer
  • Regular Expressions
  • Return behavior in PowerShell
  • Running Executables
  • Scheduled tasks module
  • Security and Cryptography
  • Sending Email
  • SharePoint Module
  • Signing Scripts
  • Special Operators
  • Switch statement
  • TCP Communication with PowerShell
  • URL Encode/Decode
  • Using existing static classes
  • Using ShouldProcess
  • Using the Help System
  • Using the progress bar
  • Variables in PowerShell
  • WMI and CIM
  • Working with Objects
  • Working with the PowerShell pipeline
  • Working with XML Files

PowerShell Operators Assignment Operators

Fastest entity framework extensions.

Simple arithmetic:

Increment and decrement:

Got any PowerShell Question?

pdf

  • Advertise with us
  • Cookie Policy
  • Privacy Policy

Get monthly updates about new articles, cheatsheets, and tricks.

  • Press Releases
  • Privacy Policy
  • Magazine Home
  • CODE Focus Magazine
  • My (Digital) Magazines
  • Where is my Magazine?
  • My Subscriber Account
  • Consulting Home
  • Services & Technologies
  • Artificial Intelligence (AI)
  • Cloud Computing
  • Custom Application Development
  • Executive Briefing (AI)
  • Low-Code/No-Code
  • Cyber Security
  • Copilots in Your Apps!
  • Project Rescue
  • Business Document Copilot
  • Legacy Conversion and Maintenance
  • Free Hour of Consulting
  • VFP Conversion
  • Energy Software
  • Staffing Home
  • Our Services
  • Training Home
  • State of AI
  • CODE Presents
  • State of .NET
  • Lunch with CODE
  • Framework Home
  • Get Started & Documentation
  • Support & Services
  • VFP Conversion Home
  • Fox End of Life

assignment operators powershell

Using PowerShell Operators

assignment operators powershell

Published in:

assignment operators powershell

Filed under:

Like any other programming language, operators are a basic building block of PowerShell. When creating a script or module, chances are that you'll find that you need a PowerShell operator. There are several types of operators that can be used in PowerShell. For instance, there are operators for comparing values, operators for performing arithmetic, logical operators for comparing conditions, and, of course, operators for manipulating strings.

In this article, I'll go over the most common operators along with various examples of how they can be used. For further reading, take a look at the Microsoft help page too .

Assignment Operators

Variables are often used in PowerShell and they're created using the assignment operator. The simplest example of an assignment operator is the equal sign ( = ), which is used to assign a variable. Here, I assign a string to the variable $Testvar:

To add and remove items for a variable, use the add-equals ( += ) and subtract-equals ( ?= ) operators. In this example, I first assign 1 to $a , then add 2 and remove 1 , which leaves the variable with a value of 2 .

An interesting note is that if PowerShell contains only one object in a variable, the variable is automatically the data type of that object. This can be seen with the variable $a as the GetType method is used to display it is an integer:

To show the more standard arithmetic operators as well as how PowerShell gives precedence, consider this next example. First, the operation in the parentheses is processed ( 10-1 ) to equal 9 . Next, 1 is multiplied by 5 and then 2 and 5 are added together. Finally, that sum ( 7 ) is added with 9 to give a result of 16 .

The simplest example of an assignment operator is "=", which is used to assign a variable.

Comparison Operators

In PowerShell, comparison operators are commonly used to compare conditions for equality, matching, containment, and replacement. These operators, like the majority of other operators, are prefixed with a hyphen (-) such as -eq , which is used to verify if two values are equal.

To illustrate this, let's compare two variables against each other.

Because $a and $b are equal, the output will be These are equal!

In this next example, two date objects are compared with the greater than operator, which is -gt . The variable $Today gets the immediate date and time, and $Yesterday is used with the AddDays method to put the date and time to the day before. If you copy and paste this into the PowerShell console, the correct output is displayed as in Figure 1 :

Figure 1 : Using -gt with dates

In PowerShell, comparison operators are very commonly used because they provide a technique for comparing conditions for equality, matching, containment, and replacement.

Table 1 shows additional examples of equality operators found in PowerShell.

Matching operators in PowerShell are used to compare strings against both wildcards and regular expressions to find a match. There are four operators in this category: -like , -notlike , -match, and -notmatch . In this next snippet, I create a foreach loop and go through each process running on my local system to see if any match “Drop*” using a wildcard.

The output is a match for the Dropbox and Dropbox Web Helper processes.

For replacing part of a value in a string with another string the “-replace” operator is used.

Containment operators help find out whether a collection of objects contains a specific value, and if so, returns a Boolean after the first finding of the value. For example, -contains is used to find the process “powershell” in a list of processes. In this example the “powershell” process occurs twice in the list of processes; “True” is returned after finding the first instance.

Similar to the -contains and -notcontains operators, PowerShell also provides -in and -notin, although these work pretty much the same. The only difference is the order in which they're used in relation to the collection and test value. With -notin, the test value must be used before the collection:

For replacing part of a value in a string with another string, the -replace operator is used. A simple example is the following snippet, which replaces the string this with that. Note the first parameter after -replace is the value to find and the second is the value to replace it with.

Logical Operators

In PowerShell, logical operators are used to connect and test multiple expressions and statements. Logical operators are excellent if testing is needed for complex expressions. Here, the output of Get-Process is piped to Where-Object and filtered with the -and operator to connect to find processes that start with Drop and don't start with Dropbox Web . The result is that Where-Object filters out the Dropbox Web Helper process but not Dropbox and DropboxUpdate, as shown in Figure 2 .

Figure 2: Using -and to filter processes

Two other logical operators are -or and -not (which can be used as ! as well). In this if statement, the condition being tested is if either the “foo” or “powershell” process isn't found to be running with Get-Process , the output True is returned. Because the process “foo” isn't running (even though the “powershell” process is), the output is True.

Note that if the -or operator is changed to -and, keeping all the other if statement the same, the condition is false because both processes would need to be running for it to be true.

One simple way to think of the difference between -or and -and is that -or means that just one aspect needs to be true in the statement, and -and means that all aspects of the conditions being tested need to be true.

When creating a script or module, chances are, you'll find that using a PowerShell operator is needed.

Split and Join Operators

To split and join strings to PowerShell, the -split and -join operators are used. These two operators are very commonly used in PowerShell scripts because this type of operation is necessary to manipulate strings. A simple example is taking a string that's formatted in a sentence and using -split to split the string at each blank space.

To best illustrate the -join operator, the previous string sentence can be placed into a variable and then concatenated to form the original string. Note the delimiter after the -join operator is " " indicating a space between strings.

Another option for using -split is adding a script block after the operator. For instance, to split a string at either a comma or period, the -or operator can be used. In Figure 3 , the string in $test is split in this exact way.

To split and join strings to PowerShell, the “-split” and “-join” operators are used.

Figure 3: Splitting strings in PowerShell

Much like the rest of the language, PowerShell operators are fairly easy to understand and use. Understanding the range of PowerShell operators and how they're used can help you build efficient and effective code. Operators offer ways to string together complex expressions in PowerShell.

Table 1: Other examples of equality operators in PowerShell

OperatorDescription
-neNot equal to
-geGreater than or equal to
-ltLess than
-leLess than or equal to

This article was filed under:

This article was published in:.

assignment operators powershell

Have additional technical questions?

Get help from the experts at CODE Magazine - sign up for our free hour of consulting!

Contact CODE Consulting at [email protected] .

assignment operators powershell

How-to: Variables and Operators (add, subtract, divide...)

In PowerShell, all variable names start with the “$” character. Creating a new variable can be done in several ways:

$ MyVariable = SomeValue $ MyVariable = "Some String Value " [ DataType ]$ MyVariable = SomeValue New-Item Variable:\ MyVariable -value SomeValue New-Variable :\ MyVariable -value SomeValue

Multiple variables can be initialised in a single line, this will create var1 and var2:

$var2=($var1=1)+1

Variable names containing punctuation, can be handled with the syntax ${ MyVari@ble } = SomeValue However if the braces ${ } contain a colon ":" then PowerShell will treat the variable as a PATH and store the values directly in that file. ${ C:\some_file.txt } = SomeValue

Operators allow you to assign a value to the variable, or perform mathematical operations:

PowerShell will follow normal arithmetic precedence working left to right, parentheses can be used override this.

$myPrice = 128 $myPrice += 200 $myItem = "Barbecue grill" $myDescription = $myItem + " $ " + $myPrice $CastAsString = "55" $yesterday = Get-Date((Get-Date).addDays(-1)) -format yyyyMMdd $myHexValue = 0x10 $myExponentialValue = 6.5e3

Strongly typed

Forcing the correct Data Type can prevent/trap errors in later calculations. [int]$myPrice = 128 [string]$myDescription = "Barbecue grill" [string]$myDescription = 123 [string]$myDate = (Get-Date).ToString("yyyyMM") $([DateTime] "12/30/2009") $([DateTime]::Now) [datetime]$start_date=[datetime]::now.date.addDays(-5) When creating strongly typed variables it can be helpful to indicate the datatype in the variable name: $strProduct or $intPrice
In PowerShell V3.0, you can specify a range of valid attributes for any variable: PS C:\> [ValidateRange(1,10)] [int]$x = 1 PS C:\> $x = 11 The variable cannot be validated because the value 11 is not a valid value for the x variable. At line:1 char:1 + $x = 11

Array variables:

$myArray = "ars", "longa", "vita", "brevis" PowerShell can also assign values to multiple variables: $varX, $varY = 64 $varA, $varB, $varC = 1, 2, 3 That will assign 1 to $varA, 2 to $varB, and 3 to $varC.

Script blocks

An entire script block can be stored in a variable: $myVar = { a bunch of commands } Then run/call the script using & PS C:\> & $myVar You can take this one step further and turn the script block into a Function or Filter .

Reserved Words

The following may not be used as variable identifiers (unless surrounded in quotes) break, continue, do, else, elseif, for, foreach, function, filter, in, if, return, switch, until, where, while.

“Most variables can show either an upward trend or a downward trend, depending on the base year chosen” ~ Thomas Sowell

Related PowerShell Cmdlets

How-to: Automatic variables - Variables created and maintained by PowerShell $_, $Args, $Error, $Home etc. How-to: Environment variables - Windows environment variables Env: How-to: Parameters - Command Line Arguments %1 %~f1 How-to: Preference variables - Preferences: Verbosity, Confirmations, ErrorAction, $Debug. How-to: Reference variables - Pass values to a function. How-to: Concatenation - Methods to combine strings together. How-to: PowerShell Operators - Advanced Operators for Arrays and formatting expressions. Set-PSBreakpoint - Set a breakpoint on a line, command, or variable. Get-Item Variable: Clear-Variable - Remove the value from a variable. Get-Variable - Get a PowerShell variable. New-Variable - Create a new variable. Remove-Variable - Remove a variable and its value Set-Variable - Set a variable and a value.

assignment operators powershell

PowerShell Tutorial

  • PowerShell Tutorial
  • PowerShell - Home
  • PowerShell - Overview
  • PowerShell - Environment Setup
  • PowerShell - Cmdlets
  • PowerShell - Files and Folders
  • PowerShell - Dates and Timers
  • PowerShell - Files I/O
  • PowerShell - Advanced Cmdlets
  • PowerShell - Scripting
  • PowerShell - Special Variables
  • PowerShell - Operators
  • PowerShell - Looping
  • PowerShell - Conditions
  • PowerShell - Array
  • PowerShell - Hashtables
  • PowerShell - Regex
  • PowerShell - Backtick
  • PowerShell - Brackets
  • PowerShell - Alias
  • PowerShell Useful Resources
  • PowerShell - Quick Guide
  • PowerShell - Useful Resources
  • PowerShell - Discussion
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

Powershell - Assignment Operators Examples

The following scripts demonstrates the assignment operators.

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Everything you wanted to know about the if statement

  • 7 contributors

Like many other languages, PowerShell has statements for conditionally executing code in your scripts. One of those statements is the If statement. Today we will take a deep dive into one of the most fundamental commands in PowerShell.

The original version of this article appeared on the blog written by @KevinMarquette . The PowerShell team thanks Kevin for sharing this content with us. Please check out his blog at PowerShellExplained.com .

Conditional execution

Your scripts often need to make decisions and perform different logic based on those decisions. This is what I mean by conditional execution. You have one statement or value to evaluate, then execute a different section of code based on that evaluation. This is exactly what the if statement does.

The if statement

Here is a basic example of the if statement:

The first thing the if statement does is evaluate the expression in parentheses. If it evaluates to $true , then it executes the scriptblock in the braces. If the value was $false , then it would skip over that scriptblock.

In the previous example, the if statement was just evaluating the $condition variable. It was $true and would have executed the Write-Output command inside the scriptblock.

In some languages, you can place a single line of code after the if statement and it gets executed. That isn't the case in PowerShell. You must provide a full scriptblock with braces for it to work correctly.

Comparison operators

The most common use of the if statement for is comparing two items with each other. PowerShell has special operators for different comparison scenarios. When you use a comparison operator, the value on the left-hand side is compared to the value on the right-hand side.

-eq for equality

The -eq does an equality check between two values to make sure they're equal to each other.

In this example, I'm taking a known value of 5 and comparing it to my $value to see if they match.

One possible use case is to check the status of a value before you take an action on it. You could get a service and check that the status was running before you called Restart-Service on it.

It's common in other languages like C# to use == for equality (ex: 5 == $value ) but that doesn't work with PowerShell. Another common mistake that people make is to use the equals sign (ex: 5 = $value ) that is reserved for assigning values to variables. By placing your known value on the left, it makes that mistake more awkward to make.

This operator (and others) has a few variations.

  • -eq case-insensitive equality
  • -ieq case-insensitive equality
  • -ceq case-sensitive equality

-ne not equal

Many operators have a related operator that is checking for the opposite result. -ne verifies that the values don't equal each other.

Use this to make sure that the action only executes if the value isn't 5 . A good use-cases where would be to check if a service was in the running state before you try to start it.

Variations:

  • -ne case-insensitive not equal
  • -ine case-insensitive not equal
  • -cne case-sensitive not equal

These are inverse variations of -eq . I'll group these types together when I list variations for other operators.

-gt -ge -lt -le for greater than or less than

These operators are used when checking to see if a value is larger or smaller than another value. The -gt -ge -lt -le stand for GreaterThan, GreaterThanOrEqual, LessThan, and LessThanOrEqual.

  • -gt greater than
  • -igt greater than, case-insensitive
  • -cgt greater than, case-sensitive
  • -ge greater than or equal
  • -ige greater than or equal, case-insensitive
  • -cge greater than or equal, case-sensitive
  • -lt less than
  • -ilt less than, case-insensitive
  • -clt less than, case-sensitive
  • -le less than or equal
  • -ile less than or equal, case-insensitive
  • -cle less than or equal, case-sensitive

I don't know why you would use case-sensitive and insensitive options for these operators.

-like wildcard matches

PowerShell has its own wildcard-based pattern matching syntax and you can use it with the -like operator. These wildcard patterns are fairly basic.

  • ? matches any single character
  • * matches any number of characters

It's important to point out that the pattern matches the whole string. If you need to match something in the middle of the string, you need to place the * on both ends of the string.

  • -like case-insensitive wildcard
  • -ilike case-insensitive wildcard
  • -clike case-sensitive wildcard
  • -notlike case-insensitive wildcard not matched
  • -inotlike case-insensitive wildcard not matched
  • -cnotlike case-sensitive wildcard not matched

-match regular expression

The -match operator allows you to check a string for a regular-expression-based match. Use this when the wildcard patterns aren't flexible enough for you.

A regex pattern matches anywhere in the string by default. So you can specify a substring that you want matched like this:

Regex is a complex language of its own and worth looking into. I talk more about -match and the many ways to use regex in another article.

  • -match case-insensitive regex
  • -imatch case-insensitive regex
  • -cmatch case-sensitive regex
  • -notmatch case-insensitive regex not matched
  • -inotmatch case-insensitive regex not matched
  • -cnotmatch case-sensitive regex not matched
  • -is of type

You can check a value's type with the -is operator.

You may use this if you're working with classes or accepting various objects over the pipeline. You could have either a service or a service name as your input. Then check to see if you have a service and fetch the service if you only have the name.

  • -isnot not of type

Collection operators

When you use the previous operators with a single value, the result is $true or $false . This is handled slightly differently when working with a collection. Each item in the collection gets evaluated and the operator returns every value that evaluates to $true .

This still works correctly in an if statement. So a value is returned by your operator, then the whole statement is $true .

There's one small trap hiding in the details here that I need to point out. When using the -ne operator this way, it's easy to mistakenly look at the logic backwards. Using -ne with a collection returns $true if any item in the collection doesn't match your value.

This may look like a clever trick, but we have operators -contains and -in that handle this more efficiently. And -notcontains does what you expect.

The -contains operator checks the collection for your value. As soon as it finds a match, it returns $true .

This is the preferred way to see if a collection contains your value. Using Where-Object (or -eq ) walks the entire list every time and is significantly slower.

  • -contains case-insensitive match
  • -icontains case-insensitive match
  • -ccontains case-sensitive match
  • -notcontains case-insensitive not matched
  • -inotcontains case-insensitive not matched
  • -cnotcontains case-sensitive not matched

The -in operator is just like the -contains operator except the collection is on the right-hand side.

  • -in case-insensitive match
  • -iin case-insensitive match
  • -cin case-sensitive match
  • -notin case-insensitive not matched
  • -inotin case-insensitive not matched
  • -cnotin case-sensitive not matched

Logical operators

Logical operators are used to invert or combine other expressions.

The -not operator flips an expression from $false to $true or from $true to $false . Here is an example where we want to perform an action when Test-Path is $false .

Most of the operators we talked about do have a variation where you do not need to use the -not operator. But there are still times it is useful.

You can use ! as an alias for -not .

You may see ! used more by people that come from another languages like C#. I prefer to type it out because I find it hard to see when quickly looking at my scripts.

You can combine expressions with the -and operator. When you do that, both sides need to be $true for the whole expression to be $true .

In that example, $age must be 13 or older for the left side and less than 55 for the right side. I added extra parentheses to make it clearer in that example but they're optional as long as the expression is simple. Here is the same example without them.

Evaluation happens from left to right. If the first item evaluates to $false , it exits early and doesn't perform the right comparison. This is handy when you need to make sure a value exists before you use it. For example, Test-Path throws an error if you give it a $null path.

The -or allows for you to specify two expressions and returns $true if either one of them is $true .

Just like with the -and operator, the evaluation happens from left to right. Except that if the first part is $true , then the whole statement is $true and it doesn't process the rest of the expression.

Also make note of how the syntax works for these operators. You need two separate expressions. I have seen users try to do something like this $value -eq 5 -or 6 without realizing their mistake.

-xor exclusive or

This one is a little unusual. -xor allows only one expression to evaluate to $true . So if both items are $false or both items are $true , then the whole expression is $false . Another way to look at this is the expression is only $true when the results of the expression are different.

It's rare that anyone would ever use this logical operator and I can't think up a good example as to why I would ever use it.

Bitwise operators

Bitwise operators perform calculations on the bits within the values and produce a new value as the result. Teaching bitwise operators is beyond the scope of this article, but here is the list of them.

  • -band binary AND
  • -bor binary OR
  • -bxor binary exclusive OR
  • -bnot binary NOT
  • -shl shift left
  • -shr shift right

PowerShell expressions

We can use normal PowerShell inside the condition statement.

Test-Path returns $true or $false when it executes. This also applies to commands that return other values.

It evaluates to $true if there's a returned process and $false if there isn't. It's perfectly valid to use pipeline expressions or other PowerShell statements like this:

These expressions can be combined with each other with the -and and -or operators, but you may have to use parenthesis to break them into subexpressions.

Checking for $null

Having a no result or a $null value evaluates to $false in the if statement. When checking specifically for $null , it's a best practice to place the $null on the left-hand side.

There are quite a few nuances when dealing with $null values in PowerShell. If you're interested in diving deeper, I have an article about everything you wanted to know about $null .

Variable assignment within the condition

I almost forgot to add this one until Prasoon Karunan V reminded me of it.

Normally when you assign a value to a variable, the value isn't passed onto the pipeline or console. When you do a variable assignment in a sub expression, it does get passed on to the pipeline.

See how the $first assignment has no output and the $second assignment does? When an assignment is done in an if statement, it executes just like the $second assignment above. Here is a clean example on how you could use it:

If $process gets assigned a value, then the statement is $true and $process gets stopped.

Make sure you don't confuse this with -eq because this isn't an equality check. This is a more obscure feature that most people don't realize works this way.

Variable assignment from the scriptblock

You can also use the if statement scriptblock to assign a value to a variable.

Each script block is writing the results of the commands, or the value, as output. We can assign the result of the if statement to the $discount variable. That example could have just as easily assigned those values to the $discount variable directly in each scriptblock. I can't say that I use this with the if statement often, but I do have an example where I used this recently.

Alternate execution path

The if statement allows you to specify an action for not only when the statement is $true , but also for when it's $false . This is where the else statement comes into play.

The else statement is always the last part of the if statement when used.

In this example, we check the $path to make sure it's a file. If we find the file, we move it. If not, we write a warning. This type of branching logic is very common.

The if and else statements take a script block, so we can place any PowerShell command inside them, including another if statement. This allows you to make use of much more complicated logic.

In this example, we test the happy path first and then take action on it. If that fails, we do another check and to provide more detailed information to the user.

We aren't limited to just a single conditional check. We can chain if and else statements together instead of nesting them by using the elseif statement.

The execution happens from the top to the bottom. The top if statement is evaluated first. If that is $false , then it moves down to the next elseif or else in the list. That last else is the default action to take if none of the others return $true .

At this point, I need to mention the switch statement. It provides an alternate syntax for doing multiple comparisons with a value. With the switch , you specify an expression and that result gets compared with several different values. If one of those values match, the matching code block is executed. Take a look at this example:

There three possible values that can match the $itemType . In this case, it matches with Role . I used a simple example just to give you some exposure to the switch operator. I talk more about everything you ever wanted to know about the switch statement in another article.

Array inline

I have a function called Invoke-SnowSql that launches an executable with several command-line arguments. Here is a clip from that function where I build the array of arguments.

The $Debug and $Path variables are parameters on the function that are provided by the end user. I evaluate them inline inside the initialization of my array. If $Debug is true, then those values fall into the $snowSqlParam in the correct place. Same holds true for the $Path variable.

Simplify complex operations

It's inevitable that you run into a situation that has way too many comparisons to check and your If statement scrolls way off the right side of the screen.

They can be hard to read and that make you more prone to make mistakes. There are a few things we can do about that.

Line continuation

There some operators in PowerShell that let you wrap you command to the next line. The logical operators -and and -or are good operators to use if you want to break your expression into multiple lines.

There's still a lot going on there, but placing each piece on its own line makes a big difference. I generally use this when I get more than two comparisons or if I have to scroll to the right to read any of the logic.

Pre-calculating results

We can take that statement out of the if statement and only check the result.

This just feels much cleaner than the previous example. You also are given an opportunity to use a variable name that explains what it's that you're really checking. This is also and example of self-documenting code that saves unnecessary comments.

Multiple if statements

We can break this up into multiple statements and check them one at a time. In this case, we use a flag or a tracking variable to combine the results.

I did have to invert the logic to make the flag logic work correctly. Each evaluation is an individual if statement. The advantage of this is that when you're debugging, you can tell exactly what the logic is doing. I was able to add much better verbosity at the same time.

The obvious downside is that it's so much more code to write. The code is more complex to look at as it takes a single line of logic and explodes it into 25 or more lines.

Using functions

We can also move all that validation logic into a function. Look at how clean this looks at a glance.

You still have to create the function to do the validation, but it makes this code much easier to work with. It makes this code easier to test. In your tests, you can mock the call to Test-ADDriveConfiguration and you only need two tests for this function. One where it returns $true and one where it returns $false . Testing the other function is simpler because it's so small.

The body of that function could still be that one-liner we started with or the exploded logic that we used in the last section. This works well for both scenarios and allows you to easily change that implementation later.

Error handling

One important use of the if statement is to check for error conditions before you run into errors. A good example is to check if a folder already exists before you try to create it.

I like to say that if you expect an exception to happen, then it's not really an exception. So check your values and validate your conditions where you can.

If you want to dive a little more into actual exception handling, I have an article on everything you ever wanted to know about exceptions .

Final words

The if statement is such a simple statement but is a fundamental piece of PowerShell. You will find yourself using this multiple times in almost every script you write. I hope you have a better understanding than you had before.

Additional resources

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Prefix Assignment Operator in Powershell

So powershell (and most languages) have an assignment by addition operator that works with string by adding the new string to the tail of the original

For example this:

Will do the same thing as this:

Is there an operator that can do the same thing, but by prefixing the current string?

Of course, I can do the following, but I'm looking for something slightly terser

KyleMit's user avatar

PowerShell doesn't - but the .NET [string] type has the Insert() method :

You still can't shortcut the assigment though, it would become:

Alternatively, create a function that does it for you:

And in use:

Although I'd generally recommend against this pattern (writing back to variables in ancestral scopes unless necessary)

Mathias R. Jessen's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged powershell syntax or ask your own question .

  • The Overflow Blog
  • The evolution of full stack engineers
  • One of the best ways to get value for AI coding tools: generating tests
  • Featured on Meta
  • User activation: Learnings and opportunities
  • Site maintenance - Mon, Sept 16 2024, 21:00 UTC to Tue, Sept 17 2024, 2:00...
  • Staging Ground Reviewer Motivation
  • What does a new user need in a homepage experience on Stack Overflow?

Hot Network Questions

  • What film is it where the antagonist uses an expandable triple knife?
  • How to prove that the Greek cross tiles the plane?
  • why the eigen values of a random matrix are not the same?
  • How is switching of measurement ranges in instruments, like oscilloscopes, realized nowadays?
  • Does hydrogen peroxide work as a rocket fuel oxidizer by itself?
  • Paying a parking fine when I don't trust the recipient
  • How can a D-lock be bent inward by a thief?
  • Why would the GPL be viral, while EUPL isn't, according to the EUPL authors?
  • Is it a correct rendering of Acts 1,24 when the New World Translation puts in „Jehovah“ instead of Lord?
  • Exam class: \numpages wrong when enforcing an even number of pages
  • Why does documentation take a large storage?
  • Second cohomology of nonabelian finite simple group vanishes.
  • Why is resonance such a widespread phenomenon?
  • Why is the area covered by 1 steradian (in a sphere) circular in shape?
  • PCB layout guidelines Magnetic Sensor
  • How can I support a closet rod where there's no shelf?
  • How would platypus evolve some sort of digestive acid?
  • Example of two dinatural transformations between finite categories that do not compose
  • How did NASA figure out when and where the Apollo capsule would touch down on the ocean?
  • Are data in the real world "sampled" in the statistical sense?
  • BASH - Find file with regex - Non-recursively delete number-only filenames in directory
  • NSolve uses all CPU resources
  • Engaging students in the beauty of mathematics
  • "Tail -f" on symlink that points to a file on another drive has interval stops, but not when tailing the original file

assignment operators powershell

IMAGES

  1. PowerShell Assignment Operators

    assignment operators powershell

  2. PowerShell Operators

    assignment operators powershell

  3. PowerShell Assignment Operators

    assignment operators powershell

  4. PowerShell Tutorial with Examples 02

    assignment operators powershell

  5. PowerShell 7 Tutorial 13: Assignment Operators

    assignment operators powershell

  6. PowerShell Assignment Operators

    assignment operators powershell

VIDEO

  1. Assignment on Powershell

  2. Powershell Scripting

  3. PowerShell Comparison operators (Intro to PowerShell series video 11-5)

  4. PowerShell

  5. C++ Assignment Operators Practice coding

  6. "Mastering Assignment Operators in Python: A Comprehensive Guide"

COMMENTS

  1. about_Assignment_Operators

    The syntax of the assignment operators is as follows: <assignable-expression> <assignment-operator> <value>. Assignable expressions include variables and properties. The value can be a single value, an array of values, or a command, expression, or statement. The increment and decrement operators are unary operators.

  2. about_Operators

    The multiplication operator returns the specified number of copies of each element. You can use arithmetic operators on any .NET type that implements them, such as: Int, String, DateTime, Hashtable, and Arrays. Bitwise operators (-band, -bor, -bxor, -bnot, -shl, -shr) manipulate the bit patterns in values.

  3. PowerShell Operators [Complete Guide]

    PowerShell Operators [Complete Guide] When using PowerShell you can use a wide variety of operators in your script. They can be used in commands or expressions and are used to perform comparisons, define conditions, or assign and manipulate values. If you are using PowerShell 7, then you can also use the new Ternary operators.

  4. powershell

    Yes, the increase assignment operator (+=) should be avoided for building an object collection. (see also: PowerShell scripting performance considerations). Apart from the fact: that using the += operator usually requires more statements (because of the array initialization = @()), and

  5. about_Operator_Precedence

    The exceptions are the assignment operators, the cast operators, and the negation operators (!, -not, -bnot), which are evaluated from right to left. You can use enclosures, such as parentheses, to override the standard precedence order and force PowerShell to evaluate the enclosed part of an expression before an unenclosed part.

  6. PowerShell

    PowerShell arithmetic operators are used to calculate numeric values. These include: Operator Name Description + Addition: Adds numbers, concatenates strings and arrays.-Subtraction: ... Assignment operators can be used to assign, change, or append values to variables. These operators are a shorter syntax for assigning the result of an ...

  7. PowerShell Tutorial => Assignment Operators

    PDF - Download PowerShell for free Previous Next This modified text is an extract of the original Stack Overflow Documentation created by following contributors and released under CC BY-SA 3.0

  8. PowerShell Assignment Operators

    The assignment operators are used in the PowerShell to assign one or more values and change or append the values to the variable. These operators can perform the numeric operations before assigning the values to the variables. The most commonly used operator is an assignment operator (=), which assigns the values to the variable.

  9. Using PowerShell Operators

    These two operators are very commonly used in PowerShell scripts because this type of operation is necessary to manipulate strings. A simple example is taking a string that's formatted in a sentence and using -split to split the string at each blank space. PS C:\> "This is a test sentence to split". -split ' '.

  10. PowerShell Operators: A Comprehensive Guide

    Assignment operators are used to assign values to variables. PowerShell supports various assignment operators, including: Assignment (=): Assigns the value of the right operand to the variable on the left. Addition Assignment (+=): Adds the value of the right operand to the variable on the left. Subtraction Assignment (-=): Subtracts the value ...

  11. Variables and Operators

    However if the braces ${ } contain a colon ":" then PowerShell will treat the variable as a PATH and store the values directly in that file. ${C:\some_file.txt} = SomeValue. Operators allow you to assign a value to the variable, or perform mathematical operations:

  12. 3 Operators and expressions

    Figure 3.3 The PowerShell assignment operators. As you can see, along with simple assignment, PowerShell supports the compound operators that are found in C-based languages. These compound operators retrieve, update, and reassign a variable's value all in one step. The result is a much more concise notation for expressing this type of operation.

  13. about_Logical_Operators

    Statements that use the logical operators return Boolean (TRUE or FALSE) values. The PowerShell logical operators evaluate only the statements required to determine the truth value of the statement. If the left operand in a statement that contains the and operator is FALSE, the right operand isn't evaluated. If the left operand in a statement ...

  14. Powershell

    Powershell - Assignment Operators Examples - The following scripts demonstrates the assignment operators.

  15. PowerShell Assignment Operators

    The assignment operators are used in the PowerShell to assign one or more values and change or append the values to the variable. These operators can perform the numeric operations before assigning the values to the variables. The most commonly used operator is an assignment operator (=), which assigns the values to the variable.

  16. about_Arithmetic_Operators

    Long description. Arithmetic operators calculate numeric values. You can use one or more arithmetic operators to add, subtract, multiply, and divide values, and to calculate the remainder (modulus) of a division operation. The addition operator (+) and multiplication operator (*) also operate on strings, arrays, and hashtables.

  17. Everything you wanted to know about the if statement

    Comparison operators. The most common use of the if statement for is comparing two items with each other. PowerShell has special operators for different comparison scenarios. When you use a comparison operator, the value on the left-hand side is compared to the value on the right-hand side.-eq for equality

  18. Powershell assignment in expression?

    powershell; assignment-operator; Share. Improve this question. Follow edited Feb 6, 2022 at 1:44. Tuor. asked Feb 6, 2022 at 1:27. Tuor Tuor. 1,155 1 1 gold badge 14 14 silver badges 34 34 bronze badges. 3. 1. PowerShell can assign nearly everything to a variable.

  19. Prefix Assignment Operator in Powershell

    Prefix Assignment Operator in Powershell. Ask Question Asked 9 years, 1 month ago. Modified 9 years, 1 month ago. Viewed 594 times 1 So powershell (and most languages) have an assignment by addition operator that works with string by adding the new string to the tail of the original. For example this: ...