Operators - Can you trace this call

Operators are the part of the programming language that lets you manipulate variables. They can be used for math, comparing objects, assigning values, accessing functions, and more.

Arithmetic Operators

You already know how four the five arithmetic operators work, they're the ones you use for every day math as well as the Modulus Operator: +, -, *, /, and %.

Addition (+)

The + operator will add two numbers togethers. It can also be used for combining strings.

#Add two numbers and assign them to a Variable
$Result = 4 + 6

#Add a number to a variable
$NewResult = $Result + 9

#Add two variables together
$FinalResult = $NewResult + $Result

#Combine Two Strings
$String = "How many Roads " + "Must a man walk down"

#Combine a String and number
$NewString = "How many roads? " + 7
A demonstration of several ways to use the + operator

Note that while you can combine a string with a number using the + operator, the string has to be before the + operator. Otherwise, instead of combining them as a string, Powershell will attempt to add the two together as if they're numbers. Which will fail. Powershell determines the actions of an operator based on the type of the value to the left of the operator.

Subtraction (-)

The - operator subtracts the second value from the first value.

#Subtract one value from another
$Value = 9 - 5

$Subtract a value from a variable
$NewValue = $Value - 2

#Subtract a variable from a value
$ThirdValue = 15 - $Value

#Subtract a variable from another variable
$FourthValue = $ThirdValue - $NewValue
A demonstration of how the - operator works

Multiplication

The * operator will multiply two values together. You can also multiply a string by a value and it will return that many instances of the string (I've never had a use for this, but it exists so someone must have).

#Multiply two values together
$Output = 5 * 9

#Multiply a variable by a value
$NewOutput = $Output * 3

#Multiply two variables
$LastOutput = $Output * $NewOutput

#Multiply a string by a value
"String" * 5

#Result of this is StringStringStringStringString
A demonstration of how the * operator works

Division

The / operator divides the first value by the second value.

#Divide one value by another
$Outcome =  18 / 3

#Divide a variable by a value
$NewOutcome = $Outcome / 2

#Divide a value by a variable
$ThirdOutcome = 24 / $Outcome

#Divide one variable by another
$FourthOutcome = $ThirdOutcome / $NewOutcome
A demonstration of how the / operator works

Modulus

The % operator is the modulus operator. How it operates is it divides the first value by the second value, and then returns the remainder (remember long division?). This can be useful for determining if a value is even/odd or is a certain number of a set, among other uses.

#Use Modulus to determine if a number is odd
$isOdd = 15 % 2

#Using % 2 will divide a number by 2, and if it is divisible by two, return 0, else it will return 1. This has an added benefit of 0 evaluating as False if you compare it with a Boolean value, and 1 evaluating as True.

#Determine if number is divisible by 3
$ByThree = 19 % 3

#Unless the result is 0, the number is not divisible by three.
A demonstration of how the modulus operator works

Order of Operations

A quick note about what order the arithmetic operators evaluate in. Arithmetic operators are evaluated in the same order you learned in your math classes. Multiplication, division, and modulus are evaluated first (going from left to right), followed by addition and subtraction from left to right. Just like in your math classes, you can manipulate this order by using parentheses (), as anything in parentheses is moved to the top of the order.

#Order of Operations without Parentheses
3 + 6 / 2 * 4

#This evaluates 6 / 2 first (Result: 3) followed by 3 * 4 (Result: 12) and lastly 3 + 12 (Result: 15)

#Order of Operations with Parentheses
3 + 6 / (2 * 4)

#This evaluates (2 * 4) first (Result: 8) followed by 6 / 8 (Result: .75) and lastly 3 + .75 (Result: 3.75)
A demonstration using () to influence the order that operators are evaluated

Assignment Operators

Assignment operators are what you use to assign a value to a variable. There are three, =, +=, and -=. Equals (=) assigns the value of whatever is on the right hand side to the variable on the left hand side. Plus Equals (+=) adds the value of the right hand side to the left hand side and then assigns the result to the variable on the left hand side. Subtraction Equals (-=) subtracts the value on the right hand side from the left hand side and then assigns the result to the variable on the left hand side.

#Assign a value to a variable
$Value = 16

#Add a value to a variable and assign the result to the same variable.
$Value += 4

#Subtract a value from a variable and assign the result to the same variable
$Value -= 4
A demonstration of using the assignment operator (=), the addition assignment operator (+=) and the subtraction assignment operator (=-)

Incremental Operators

Sometimes you just need to increment or decrement a number by one. You can easily do that with the ++ and -- operators. These are shorthand for doing a += 1 or a -= 1. Depending on which side of the value you put them on determines whether or not they happen before or after the rest of the evaluation. If it is on the left hand side, it happens before other evaluations, if it is on the right hand side it happens after.

#Increment a variable by one
$Value = 0

$value++

Write-Host $Value

#increment a variable after adding it to a value

0 + $Value++

Write-Host $Value

#Increment a variable before adding it to a value

0 + ++$Value

Write-Host $Value
A demonstration of using the increment operator to manipulate a variables value

Comparison Operators

Comparison operators are what you use to compare two values. In many programming languages this is done with various symbols (==, <, >) however in Powershell it is done with named operators (-eq, -lt, -gt).

-eq

-eq  (equals) is used to determine if two values are equal to each other. If they are, it returns true otherwise it will return false. Note that the comparison operator for equals is not interchangeable with the assignment operator using the equals sign. This saves the headache of mixing them up like in some languages that use == as the comparison operator, but can confuse some people if they're used to another language.

#Output if two values are equal to each other

4 -eq 8

4 -eq 4

#Output if a variable is equal to a value
$Value = 6

$Value -eq 4

$Value -eq 6
A demonstration using the -eq comparison operator

-ne

Sometimes you just need to know if one value doesn't equal another. That's where -ne (not equals) comes in.

#Output if two values are not equal to each other

4 -ne 8

4 -ne 4

#Output if a variable is not equal to a value
$Value = 6

$Value -ne 4

$Value -ne 6
A demonstration using the -ne comparison operator

-lt and -gt

-lt (less than) and -gt (greater than) are used to determine if the left hand value is less than or greater than the right hand value. If so they return true otherwise they return false.

#Output if a value is less than another value

5 -lt 6

#Output if a value is greater than another

5 -gt 6

#Output if a value is greater than a variable
$Value = 8

10 -gt $Value
A demonstration using the -lt and -gt operators

Note that -lt and -gt are not inclusive. A number is not less than or greater than itself and so those comparisons will return false. Which leads us to...

-le and -ge

-le (less than or equal) and -ge (greater than or equal) operate almost identically to -lt and -gt except that they include the right hand value when determining the outcome.

#Determine if a value is less than or equal to a variable
$Value = 10

5 -le $Value

10 -le $Value

11 -le $Value

#Determine if a value is greater than or equal to a variable
5 -ge $Value

10 -ge $Value

14 -ge $Value
A demonstration using the -le and -ge operators

Off-by-One

Our old friend the Off-by-one error is back. When doing comparisons with -lt, -gt, -le, and -ge it can be easy to use the wrong comparison and end up being off by one number when making your comparison. -lt and -gt are exclusive operators which means that the number they are evaluating against is not included in the comparison, while -le and -ge are inclusive operators which means that the number being evaluated is included in the comparison. Mixing the two up can have unintended results in your code so make sure to use the correct set.

Logical Operators

Often you will have to make a decision off of more than one set of results, this is where logical operators come in. Logical operators are -and, -or,  -xor, and -not (or !). These are boolean (True/False) operations and are mostly used in decision making.

-and

-and will return True if both the left and right values evaluate to true, otherwise it returns false. To evaluate as true, a value just needs to be not equal to False or 0.

#Returns true if both sides evaluate to true

(6 + 15) -and (5 * 5)

(6 - 2) -and (6 - 6)

(6 -lt 17) -and (15 -gt 4)

(7 -le 7) -and (13 -ge 14)
A demonstration using -and

-or

-or will return True as long as one side of the evaluation returns true. If one or both of the values are true, it will return true, otherwise it will return false.

#Return true if one or both sides evaluate to true

(6 + 5) -or (4 + 3)

(6 - -6) -or (5 * 2)

(6 - 6) -or (2 * 0)
A demonstration using -or

-xor

Sometimes you need to know if only one side of the evaluation is true, this is where -xor comes in. -xor means exclusive or and will only return true if one side evaluates to true and the other side evaluates to false.

#Return true if only one side evaluates to true

(6 -gt 5) -xor (6 -lt 8)

(6 -gt 5) -xor (6 -lt 3)
A demonstration using -xor

-not (or !)

-not (or !) will negate the result of an evaluation, swapping true to false and false to true. This is useful because -and, -or, and -xor operate using the true value as a positive, but sometimes what you're looking for is a false value. Unlike the other logical operators, -not (or !) can be used on it's own.

#Use -not to get a False result to evaluate true in a -and
(6 -gt 5) -and -not(5 -gt 6)

(6 -gt 5) -and !(5 -gt 6)

#The two above are identical

#Use -not on its own to swap a value
-not($True)
A demonstration using -not to swap True/False values

Order of Operations

Using parentheses to group logical operators is very important as otherwise they are evaluated moving from left to right with no precedence given to any particular operator.

#Logical operators without Parentheses
$true -and $false -or $true -and $false

#This equats to False

#Logical operators with Parentheses
$true -and ($false -or ($true -and $true))

#This equates to $true
A demonstration using parentheses with logical operators

. and ..

The dot (.) operator and the range (..) operator have very different functions but are grouped together here. The dot operator is used to access instance variables and functions of an object, while the range operator is used to define a range of numbers.

#Use the dot operator to access the instance variable length of a string.
$String = "A number of characters"

$String.Length

#Use the dot operator to access the instance function Trim 

$String.Trim("ff")
A demonstration using the . operator
#Use the range operator to output a range of numbers
1..10

#Use the range operator to create an array with a range of numbers
$Array = 1..10
A demonstration using the .. operator