So what are if and else statements within PowerShell?
Well, firstly,
an if and an else statement is used to control the flow
of PowerShell execution for decisions.
So, for example, when you run a PowerShell script,
you have to make a decision and then perform different types of logic
based on the outcome of that thing that you're evaluating.
You may have a statement or value that needs to be checked,
combined with something else or validated,
and then execute different code based on different outputs of that evaluation.
In PowerShell context or encoding, this is referred to as conditional execution,
and this is where our if and else statements come from.
Now when we talk about if statements,
we can group them into three different types.
The first one is the standard if statement.
This is the regular one where there's a first test in the evaluation.
So, for example, if this something,
and then it will contain a statement of code execution after that.
And then it kind of ends, so it's a singular if this or that doesn't,
then do this.
Else just drop it out and do nothing.
The second one is to combine it with an else statement,
which effectively has a default value at the end of it.
So if the statement above doesn't pass,
then just drop it into this default piece,
where it will then execute whatever code or whatever output you've determined.
And the last one is referred to as an elseif so,
this is where we combine them all together.
So we can now say if this meets, then do that.
Elseif, which then provides additional conditions with different outcomes,
then do this, elseif do this, else, which is the default,
drop it out.
So this allows us to build quite deep structures.
Now, of course,
don't go crazy and build loads of if and elseif
statements and there's hundreds of them.
Because trust me, your code's going to take ages to execute.
But it does provide us with the ability to create quite
complex process and paths for execution.
Now, when we talk about these three different types,
the if, the elseif, and the else statements,
they're kind of made up in a logical order of components.
The first piece is the if statement.
This is the if something is going to happen,
and this is wrapped around with parentheses.
So if we're looking at it in code, it would say if,
open bracket, something in the middle, close bracket.
And the thing that's inside the brackets or the
parentheses is the bit that's evaluated.
Then we can add any elseif statements to add multiple conditions.
Then we have the else statement, which is the dropout,
or the final default value.
And then, of course, we have the actual output and value,
because we may be writing a value to the screen,
or we may be calculating something and then using that output later on.
So these statements allow us to use either or.
Now when we look at this a little bit further,
the if statement, when it executes,
it checks the result of the first test to make sure that it equals to true.
And then if it does and passes,
it will execute any kind of actions or code that
reside in that initial if statement.
If the first test result returns false,
then it will work down the tree for every other
condition to evaluate until they are true,
or if they all equal false then it just drops out to the bottom.
If the result of all the subsequent tests equals true,
then any specified actions or code is executed.
So if we have if‑else, if‑else, if‑else,
it could drop to the second or the first one,
depending what was passed.
And then, of course, as we know, if all of them fail,
it will literally just drop to that, what I refer to as the default ending,
or the else, which basically will say just execute this piece of code.
So what does that actually look like?
Well, if you look at the syntax here, I'm going to have a variable with a value.
It's just a variable called variable, and then I have an if statement.
This is the simplistic syntax.
It's if, and I'm using a variable.
Now it could just be a piece of text I write there or something else, but
predominantly you'll be validating the input of something.
So if my variable has a value,
I'm not validating what the value is; I'm just using it this way to say,
does it contain something?
If it does, then write that output,
and you can see I'm just passing that same value to the output.
So in this example, it's literally just one test and drop out.
Notice there's no else.
There's no elseif.
It's literally just an if statement.
If we were to enhance this and go with an if and an else syntax,
then of course I have my variable, which is equal to the value,
I have my first if, which we just looked at,
so if the variable contains something, then pass this,
else drop it out into the bottom.
So now what we've done is added a default path,
that if the first one fails, it will output the value.
And, of course, I've changed the message to say the check returned false.
So let's go one step further.
Let's add an elseif and an else. So now I have two variables,
variableone, variabletwo, both with values,
and I'm going to say if variableone contains a value,
then write the output, and that is the end of the code.
Elseif, so if variableone fails,
drop down to elseif and check if variabletwo has a value,
and if it does, then execute that code path.
Otherwise,
just drop it out into the else statement and write the message
that both the values don't have anything.
So you can see the structure is really, really simple,
but you can also probably get a sense of how complicated it could be,
depending on how many statements you need to kind of flow through.
So let's talk about the parentheses themselves.
So in the if statement so far, we've just used a variable,
so if this object contains something.
However,
the parentheses contain the evaluation of a condition or multiple conditions.
It can contain comparison operators, so some examples would be eq for equal,
gt for greater than, ne for not equal, like for like,
notlike, matches, etc.
We can also do a comparison of array values as well.
So if we have a‑‑‑imagine a set of numbers in a variable,
so numbers 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
we could check if a number existed in that array.
We could also do combinations of and and or.
So if we're trying to do multiple comparison and say,
well, does this value and this value or this value,
then we can do that too.
And then there's also support for multiple conditions if we need to.
So this helps us to do some very,
very deep and complex if comparisons and statements based
on multiple values that we may pass in.
So what are some of the common condition operators that are available?
Well, the first one that we kind of use the most is comparison,
so a comparison operator is used to compare values and test conditions.
The comparison operators include operators that can
find or replace patterns in text, so, for example,
using match, notmatch, replace, etc.
Or we can use regular expressions, such as like, notlike, or even wildcards.
You can also then do what's called containment comparison,
which means that we're trying to look within something to see if
the value that I have exists in something,
and this uses such as in, notin, contains,
and notcontains.
The second operator that we can use, or common condition operator,
is collection operators.
This is where we can look for values that exist in an array of
a data structure or a collection of items.
The items could be of the same type, or they could be of different types.
So your simple example here would be a folder on a file share with documents in.
So that would be a collection that we would retrieve,
and then we could iterate through them.
We also then have logical operators, which are some of the most common.
These are the logical operators such as and,
or, not, and this is to connect conditional statements into complex conditions.
So, for example,
you could use a logical and operator to then create a filter
with one or more different conditions.
We also have arithmetic operators, where this can calculate numeric values.
You can use one or more arithmetic operators to add,
subtract, multiply, and divide values,
as well as to calculate any kind of sum based on the
various numbers that you might be using.
Now from the conditions operators,
the first one that tends to get used the most is assignment.
So assignment operators are =, +=, ‑=, etc.
This is used to assign, change, or append values to a variable.
So for example, if we were iterating through numbers,
and we wanted to increase or add a value to a variable,
we can simply use += and pass the value into the variable,
and that will append to that.
We can also use what's called redirection operators.
These would be >, >>,
etc., and this is something we could do in batch files years ago where
we can basically send the output to a text file.
We can also use split and join, so this is called ‑split and ‑join operators,
where we're able to divide and combine string values
and even create substrings if needed.
We also have the type object, which is, we can use the is,
isnot, and as,
and this is all about casting and checking the .NET Framework type of the
value or the object that we retrieved in PowerShell.
We also have what's called unary operators,
which is all about incrementing or decrementing variables.
You may have seen PowerShell in the past,
where we start with a number, for example,
so like a = 1, and then we want to increment and you'll often see $a++.
That's a unary operator that will basically add another 1 to what's there.
And then, of course, our last one here is what's referred to as bitwise.
Now bitwise operators are band, bor, bxor,
bnot, etc., and this manipulates the bit patterns in the values,
so a bitwise operators act at the binary format of a value.
So, for example, if you had the number 10,
the binary value for that is 00001010.
And if you were then trying to add that or compare it to number 3,
its binary value is 00000011, so it uses that level.
Now the most common use of the if statement is
comparing two items with each other.
So PowerShell has multiple operators for the comparison scenarios,
and when you use a comparison operator,
you compare the left‑hand side's value to the right‑hand side value.
Now from a syntax perspective, let's say we have two variables.
Variable = value, and then we have a comparable variable.
If I want to check if these are equal to each other in an if statement,
I can say if, parentheses, variable,
and then we're going to use the ‑eq operator to validate.
So that test, both those would need to be exactly the same.
And of course, my value for both of those is value, so that would be successful.
I could then also change that and say, well,
is variable ‑gt comparevariable? Now what's going to happen here is
this is probably going to fail because value and value are text
values and they are equal to each other,
so one cannot be greater than the other.
This is normally used when we're using numbers.
Then of course,
we've got like, which will do a comparison check and say is
variable like the comparevariable? If it is,
then that will pass. And then we can do a match.
This is really used for string values.
So does this value match exactly that value?
So a couple of different operators that we can use for doing comparisons. Now a
comparison operator kind of returns either true or false.
Collection operators, on the other hand,
differ a little bit. As each item in the collection is evaluated, the
operator will then return whether that value is true or not.
So from a syntax perspective, let's say we have two variables here,
so I have an array.
You'll notice we're doing something new.
It says 1 . . 10.
What that does is that creates an array object of 1, 2, 3, 4, 5, 6, 7, 8, 9, 10.
And then I have my comparevariable.
So what I can do here is I can say if the current array value, so
array, something, is greater than comparevariable, then,
of course, it will return true.
So that's determining that my array variable is one
of the numbers between 1 and 10.
I can then say, well, if the array contains that number,
so slightly different approach,
we're actually trying to see if it contains the number
we're trying to compare. And then, of course,
we can flick it around the other way and say the
comparevariable, is it in the array? So a different way of
kind of comparing if the values exist.
Now logical operators are used to invert or combine other expressions.
You can connect multiple statements allowing you to use a single
expression to test for numerous conditions.
So what does that look like?
So let's say we have three variables now.
I have my base variable,
my comparevariable, and another comparevariable. In this instance,
when we're using logical operators,
you can see that we've got two equals statements
which are then combined into an ‑and,
which means that my code needs to pass both of these.
So is variableOne ‑eq the comparevariableOne? And ‑and, is
$variable ‑eq comparevariableTwo? Now, of course,
we can change that to an ‑or, which means it takes one or the other.
So either of these approaches will work, except the output or the outcome may
be different, because ‑and requires both; ‑or can be either.
Arithmetic operators obviously can calculate numeric values,
which is critical in lots of PowerShell that you may write, where you'll
need to pass values and calculate and multiply, etc.
Now, of course, when we do this in PowerShell,
if we look at the syntax here,
I've got my three variables again with just text values.
Obviously, in the real world, they would be actual numbers.
And of course, what you can see here is I'm doing a combination of things.
I'm using an arithmetic operator, which would be +, so I can say,
if my first variable + the second variable ‑gt the third variable,
then do something.
I could change that to division and then use less than. I could
also say multiply those together and then,
of course, equal to that variable.
Now of course, you can't do that with string values.
It will complain.
It doesn't know how to add those.
So when we actually write the PowerShell out we'll utilize numbers instead.
Now another operator that's available to us is what's called the turnary
operator. Now PowerShell 7 upwards introduced a new syntax for using if and
else instead of writing if and else. So first off,
we have the condition, the same as you would normally.
So the condition expression gets evaluated and the
result returns a Boolean value.
Then we have a true expression, so if it passes that true,
then it will execute the specific code path.
And then, of course, we have a false execution as well, so if it fails the true,
then it will execute this, so very much the same as an if‑else statement.
This syntax, however, is very different.
So let's take a look at our three variables.
I have variableOne with a number, variableTwo with a number,
and then a text variable with the word true.
Now what we can see is, I have a couple of different options here.
So the first one, notice I'm just using parentheses,
and I say,
if value 1 is equal to value 2 and then if we ignore
the question mark for a second, it says $true : $false.
Now think of our logic.
Imagine you're writing an if‑else. The if would be before the
parentheses, so if variableOne ‑eq variableTwo,
and then the question mark is the true path.
So the question mark says, well, if it's true,
do this, and the colon is the false.
So the second one here, for example, I've gone a little bit further.
It says variableOne ‑eq availableTwo. If it's true,
write out some text values that say variableOne >
variableTwo. Else, variableOne < variableTwo.
Now, of course, we can also do this with a text value as well.
So we can say, you know, remember we put in parentheses,
text variable or the variable name that just says if
something exists? So in this one,
I'm just saying is there a value? which is true. It will
then write the message, Value is true.
Else, the value is false.
This works great for inline PowerShell as you're writing
things out. It's also significantly less than writing lots of
isif and else and elseif statements. And so this works out really, really well.