PowerShell While loops explained for Absolute Beginners

A “while” back (see what I did there?) I wrote a short blog post explaining PowerShell foreach loops for absolute beginners. The target audience for that post (and this one) is absolute PowerShell beginners. These are users who are just starting to understand how to use the building blocks of the language. Luckily, some of these building blocks are the same for any programming language, such as a “while” loop. So, if you happen to understand “while” loops in another language it will be roughly the same in PowerShell. Today, I will explain the concept with an analogy. Slot machines.

Concept

So let me set up this scene. You are in a casino with a bag of quarters, searching for a slot machine to dump your hard-earned money into knowing full well you will undoubtedly lose it all. You come up to your favorite slot machine and say to yourself “I am not leaving this machine until I win some money”. Basically, you are going to keep pumping in quarters and pulling that stupid lever until it spits some money back out at you.

via GIPHY

So, you sit down, put in a quarter, pull the lever. Repeating this task over and over again until you win back money. Then once you win back any sum of money, get up and leave the machine.

This is a great analogy for a “while” loop. Running the same task over and over again until a condition is met that you specify. In this case, winning any sum of money is the condition.

PowerShell Example

If we were to code this real-world example into PowerShell it would be something like this:

Here, the command Start-SlotMachineAttempt indicates putting in your quarter and pulling the lever on the “Wheel of Fortune” slot machine. It then stores the property “Result” in the variable $SlotResult. PowerShell will keep running this command until the value of $SlotResult is “Win”. See? Very simple in concept!

Now you know how the while loop works in PowerShell but also remember that playing slot machines is an insanely stupid idea and you are doomed to lose your money.

Trackbacks & Pings

Leave a Reply

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