Hello! (I don’t have any witty thing to call you dear reader. Not today)

So today we are going to talk about some other conditional statements. Last post (Which, incidentally was forever ago, I mean what the hell man, why are you not posting more often????) we only went over ifthen statements. We also covered else briefly but it was a crappy explanation, sooo… Good luck with that (I’m kidding!!). Additionally there are the statements for, foreach, while, and finally elseif. In this post we will cover else and elseif! (There are some more that sort of fall into this category, but we are going to call them ‘special statements’ and they include trycatchfinally, break, return, and lastly switch. But these will be covered in a further post way down the line as they are primarily for error catching and handling.)

Let’s begin by looking at else in more detail (See? I told you I was kidding!). The else statement is placed at the end of ifthen statements to act as a catch all. If we run a standard ifthen statement without a. else AND the if (statement) returns false, no code is executed and our script does nothing. Let’s jump to the “Crayon Corner.”

(I’ve decided I’m going to call all the code segments the “Crayon Corner” from now on…)

dealwithit

We are going to write a basic script again. This time we are going to check to see if one time of day is greater than another. Our script will look like this (And FYI, I am using a method called .AddDays(5) which does exactly what you suspect it does. It adds five days to the date it is getting.):

$dateLater = (Get-Date).AddDays(5)
$dateNow = Get-Date
if($dateLater -gt $dateNow)
    {
    return $true
    }

And as you’ll see, when we run this code we get a return of $true:

date1

(I’m not entirely certain that I’ve explained this before, so I’ll throw it out now. The expression “-gt” stands for greater than. In PowerShell you don’t use <, >, =. Instead you use -lt, -gt, -eq, and others. This isn’t incredibly important beyond knowing that -gt stands for greater than.)

Now, let’s make a slight change to our code, specifically changing the position of $dateLater and $dateNow so that the ifthen, statement is now not true.

$dateLater = (Get-Date).AddDays(5)
$dateNow = Get-Date
if($dateNow -gt $dateLater)
    {
    return $true
    }

And as you can see with the handy image below, we don’t get a $true anymore:

Date2

Now, let’s bring it around town! (Spongebob references, yep that is the kind of classy ((With a ‘k’)) on this blog) As we can see, we aren’t getting the other half of our pair returned. What happened to $false???

Well we haven’t told the code to give us a $false if the statement isn’t true. So how do we do that? Well let’s add our else statement! (It’s about damn time)

$dateLater = (Get-Date).AddDays(5)
$dateNow = Get-Date
if($dateNow -gt $dateLater)
    {
    return $true
    }
else
    {
    return $false
    }

And of course, when we run this code we finally get our $false:

date3

Now, I know what you are saying, “Dude! What the hell… Couldn’t I just use another ifthen statement to accomplish this exact same thing?” The answer is, Yes! Yes you can! But it can make for A LOT more coding. Let’s look at the example from the last blog:

$numberOfApples = Get-Apples -jpeg ".\applepile.jpeg"
if($numberOfApples -eq 7)
    {
    return $true
    }
if($numberOfApples -eq 1)
    {
    return $false
    }
if($numberOfApples -eq 2)
    {
    return $false
    }
if($numberOfApples -eq 3)
    {
    return $false
    }
if($numberOfApples -eq 4)
    {
    return $false
    }
if($numberOfApples -eq 5)
    {
    return $false
    }
if($numberOfApples -eq 6)
    {
    return $false
    }

That is a lot of useless code (And also, what happens if, god forbid, you have more than seven apples in your pile? You are going to get absolutely nothing again!)!

I’m going to take this moment to share some advice I’ve gotten from much more experienced coders, NEVER, and I mean NEVER (SERIOUSLY, LITERALLY, ESPECIALLY, AND MORE CAPS HERE) EVER (ok, I’m done now) copy paste code. It is a few things; one, a terrible habit to get into; two, going to cause bugs in your code; three, a management nightmare (I.E. if you want to change your code later you have to change it EVERYWHERE you copy pasted); four, lazy as hell (Ok, maybe that isn’t that bad… but this is a tutorial blog so I am trying to be good.); and finally, really difficult to read. (This last point is really important, as you learn you will read other peoples scripts and modify them to make your own… You will learn to hate people who copy paste code because it is really difficult to read and understand.) I hope that this paragraph has driven home the point that you should never use CTRL + C, CTRL + V when you are coding.

This is a really long way of putting it… But you can just use the else statement instead of a a whole lot of ifthen statements. This brings us to the next statement I promised to cover. elseif!

Elseif is the same basic statement as ifthen, except it introduces a new idea to our programming repertoire , “Flow Control.” Flow control is the primary method of saving processor resources, it allows us to distinguish sloppy code from good code, and is generally an important thing to keep in mind as you create more and more complex scripts. Flow control itself is an extremely in depth topic that is waaaay beyond the scope of this post, and probably this blog. (But I can dream) So for now we’ll just explain it as it relates to elseif.

When we make an ifthen statement, the computer has to check to see if the statement is true, (And …then process the code if it is.) this takes some processor cycles. If you have a lot of ifthen statements, it will need to process all of them individually. Let’s make some changes to our date comparison script to have it return a few things instead of just being static (And we’ll go ahead and make it interactive because that is a lot more fun!)(BACK TO THE CRAYON CORNER!):

[Datetime]$date1 = Read-Host "What is the first date?(Please format with MM/DD/YYYY)"
[Datetime]$date2 = Read-Host "What is the second date?(Please format with MM/DD/YYYY)"
if($date1 -gt $date2)
    {
    Write-Host -ForegroundColor Green "The first date is later than the second date."
    }
if($date1 -lt $date2)
    {
    Write-Host -ForegroundColor Green "The second date is later than the first date."
    }
if(($date1 -ne $null) -and ($date1 -eq $date2))
    {
    Write-Host -ForegroundColor Green "The dates are the same!"
    }
else
    {
    Write-Host -ForegroundColor Red "You didn't format the dates properly!"
    }

Now if we run this code we get some pretty interesting things:

newdate

First, you’ll notice that we are getting a bug! (Yay our first bug!!!) We are getting it to reply and tell us that our second date is larger than our first, but we are also getting a reply saying we didn’t format our dates properly! What the heck is going on here? Well, now I’m going to go ahead and spend some time drawing out a diagram to show how the code is processed. (This will take a bit, but luckily for you, you won’t notice! This is what I like to call movie mag… I mean text post magic!)

IFFlow

Another way to think about it is it processes like these statements:

“Is the first date greater than the second date?” $false (Ignore code)
“Is the second date greater than the first date?” $true (Execute code) (This gives us our green text response)
“Is the first date the same as the second date?” $false (Ignore code)
“Is the third question false?” $true (Execute Code) (And this give us our bug)

The reason it is doing this is because the else statement is only linked to the immediately previous ifthen statement. If we want our else statement to be linked properly, we need to use our elseif statement! (Yeah, this is the second part of elseif, it links a bunch of statements together… I totally talked about it up there though, just don’t re-read it… It’s been there the whole time, I promise!) So, let’s mod up our code one more time and make it full of elseif statements:

[Datetime]$date1 = Read-Host "What is the first date?(Please format with MM/DD/YYYY)"
[Datetime]$date2 = Read-Host "What is the second date?(Please format with MM/DD/YYYY)"
if($date1 -gt $date2)
    {
    Write-Host -ForegroundColor Green "The first date is later than the second date."
    }
elseif($date1 -lt $date2)
    {
    Write-Host -ForegroundColor Green "The second date is later than the first date."
    }
elseif(($date1 -ne $null) -and ($date1 -eq $date2))
    {
    Write-Host -ForegroundColor Green "The dates are the same!"
    }
else
    {
    Write-Host -ForegroundColor Red "You didn't format the dates properly!"
    }

And of course, our nice image of the code in action:

newdate2

Coolio!

meme

To explain it all though, we need to look at the flow of code processing again. (Go go text post magic!!!)

ELSEIFFlow

And finally in our text version:

“Is the first date larger than the second date?” $false (Ignore code) “Is this statement $true?” $false (Continue to process code)
“Is the second date larger than the first date?” $true (Execute code) “Is this statement $true?” $true (Stop processing all code)

If the second line was $false, the third line would be processed, and of course if the third was $false… (You get the picture… Right…? RIGHT???)

So this concludes the else and elseif statements. Tune in next time for… for, foreach, and while!!

Leave a Reply

Your email address will not be published. Required fields are marked *