Hello readers of the text below!

There is possibly going to be a fourth one as well… Man these are getting out of hand. But I guess to be fair, conditional (statements) logic is a very expansive topic… And if I want to cover it with any real detail or explanations, I need to break it up. So what is on the agenda for today? For, Foreach, and While!

Our first stop on the fun train today is going to be foreach! The logic in a foreach loop is like this: foreach thing in this group of things, do something! (Man the thing with the thing is a thing in the thing… I actually talk like this sometimes.) This probably doesn’t make a great deal of sense as is, so let’s go to the Crayon Corner:

$services = Get-Service
foreach($service in $services)
    {
    if($service.Status -like "Stopped")
        {
        Write-Host -ForegroundColor Red "$($service.Name) is stopped!"
        }
    elseif($service.Status -like "Running")
        {
        Write-Host -ForegroundColor Green "$($service.Name) is running!"
        }
    else
        {
        Write-Host -ForegroundColor Blue "$($service.Name) is in an unknown status"
        }
    }
The first thing the astute among you will notice is that I am using a real PowerShell cmdlet, "Get-Service." If you open your PowerShell window up and type Get-Service, it will return a lot of stuff, like this:
Get-Service

In our code we are loading them up into a variable, which, you should remember (If you don’t, I highly suggest that you go back and read my posts on variables located here and here. They are pretty integral to understanding what is happening with these statements.) will create a $var type of [array]. This is the core to what a foreach loop does. It breaks apart an [array] and allows you to process specific pieces of code on the individual objects contained within it.

In our example above we are having each object report whether they have a status of “Running” or “Stopped.” If it returns “Running,” it uses the object.Name to state the name, puts the text in green, and tells us it’s running. If it returns “Stopped,” we get the same service name, red text (Uh oh!) and a message telling us it’s stopped. Lastly, you’ll see the else statement which is used as a good catch all. (It is primarily if a service happens to be stopping, paused, or starting it will show up in blue and let us know the status.) If we run our code against the laptop I am typing this message on, we’ll see that we get this back:

script1

Holy crap! Look at all that color!!! And it is all based on information we got from the generated command. (I.E. CODE!)

Now you know! And

knowing-is-half-the-battle

Onto the next one! The elusive for loop!

So for loops are an interesting beast. They exist primarily to allow you to run a command a certain number of times. In our first example we will teach a computer how to count! (Seriously… It takes several instructions to get a computer to do something as simple as count… What the hell computer, my five year old is smarter than you!) To the crayon corner!

for($i=0; $i -lt 100; $i++)
    {
    Write-Host "$i !"
    }

As we can see we have a slightly more complex code syntax for our for loop. I want start by saying, I declared that variable $i. (I always put these disclaimers in because I used to be so confused about where the hell new variables came from) It had no value before I put it in there. The first part, ($i=0;, is declaring $i’s [int] value. This can be any [int] value we’d like, but for simplicity sake we will often want to use 0. The exception to this is when we are having violent battles with lawnmowers, or running like chickens with our heads cut off to save some stupid princess (WHO IS ALWAYS IN ANOTHER CASTLE!! What the hell Peach!?). Then we will want something more like a countdown timer. Here is a great example of a countdown timer.

for($i=20; $i -gt 0; $i--)
    {
    Start-Sleep -Seconds 1
    cls
    Write-Host "$i !"
    }
countdown!

And when we put that code into a PowerShell window, we get this:

The second part of our for loop is the $i -lt 100;. (Or $i -gt 0 from the last one) This is where we declare how long the for loop will run. What this is basically saying is, “Run until this condition is $false.” Once it’s satisfied it kicks us out of our loop. (Yep, once it sees $false it drops the code like a bad habit! … That was a lame joke… Like a hot potato! … Nope still lame. Uh… Like my pants when my girlfriend let’s me know… “It’s business time, yeah it’s business time!” Woo! Flight of the Conchord references. That’ll do.) (Also, don’t worry if you are confused still, read on, I’ll bring it all together at the end.)

The last part is the $i++. This is where we declare how the condition is going to be fulfilled. I’ve used both $i++ and $i– however you can make any sort of math declaration you’d like. (Specifically putting ++ or — after an [int] will add or subtract one each pass.) So you could make a statement like this:

for($i=1; $i -lt 20; $i += 2)
    {
    if((($i % 2) -ne 0) -and (($i % 3) -ne 0) -or ($i -eq 3))
        {
        Write-Host "$i is a prime!"
        }
    }
primes

And if you run this code you get something like this:

(There are probably a couple new concepts in this that don’t make much sense, don’t worry about them. I might delve into operands at some point but that is way beyond the scope of this post.)

So let’s put it all together! ($i = 1; states that we are starting at 1. $i -lt 100; states that we will continue to loop until $i is no longer less than 100. And finally! $i++ states that each loop will add 1 to $i so that it will eventually reach the condition to stop the loop.

As a final note on this, be cognizant of your logic in the loops, one of the leading causes of bugs in software is having a for loop continue endlessly causing applications to hang.

We now know all about foreach loops and for loops… It’s time for the splendid while loop! This loop is similar to the for loop above, however we just don’t define nearly as much. Basically the logic goes like this, “While condition is true, do this thing.”

Let’s take our final trip to the crayon corner and I’ll show some good examples. (Or probably terrible examples, but you must like what you see if you’ve read this far. Yeah… You know you like what you see… It’s hot!):

$i = 0
while($i -lt 100)
    {
    Write-Progress -Activity "Example activity here!" -Status "Some status here!" -PercentComplete $i
    Start-Sleep -Milliseconds 50
    $i++
    }
progress

And when we run that into our PowerShell window we get this:

While has a million more uses, but that is basically how you think about it!

This concludes the bulk of the conditional logic types. There is a few more, but you should be able to get most of your scripting and programming needs met with these.

This is the third part of my series (That took for freaking ever to publish.). If you want to read the rest you can find them here:
Conditional Logic Part 1
Conditional Logic Part 2

Leave a Reply

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