Powershell – Introducing ITPros to Developer Terms – Part 10 – Going Loopy – Do While / Do Until

Powershell-thumb[2] 

*** WARNING! ***
*** This Blog Post will talk about Developer Terms ***
*** ItPros are cautioned to break out their (Patent Pending) ***
*** “Peril Sensitive Sunglasses” (Ala the HitchHikers’ Guide to the Galaxy) ***
*** Before Reading further. If you are amongst the Bold and the DARING and the ***
*** Truly Devil May Care of ITPros, Please feel free to Read on and live Daring! ***

But don’t say I didn’t warn you 🙂
Sean – The Energized Tech

 

Ah excellent, you’ve all returned.   I see you have either decided to learn more or you have come seeking a refund.  

Well since this added to a deposit of $NULL

Oh? You understood that term?  Move to the top of the class.  Because today we’re going to show you two loops for the price of one.  THAT’S Right! TWO!

Well really, they are two that are so similiar, that if you know one?  The other is it’s opposite.  Like Laurel and Hardy, Abbott and Costello, ITPros and Developers!

The Do While and Do Until loops in Powershell (Like in other languages work on two premises.  Keep doing this WHILE a condition is true (IE: WHILE the Boss is angry, pretend to work) or UNTIL a Condition is Reached (UNTIL the Boss catches you Twittering and Blogging at your Desk, Keep going at it)

WHILE is easy it looks like this

WHILE ( $CONDITION –eq $TRUE ) { CODE; CODE; CODE }

So a good example of WHILE in action could be (and this a good example of “Validation”)

$USERNAME=$NULL

WHILE ( $USERNAME –ne ‘QUIT’ ) {

$USERNAME=READ-HOST ‘Enter User Name’
#
# HERE YOU COULD EXECUTE SOME REALLY IMPRESSIVE SCRIPT
# THAT DOES SOMETHING AMAZING AND ASTOUNDING WITH
# THAT USERNAME.  Any Ideas?

}

Now in truth that is a HORRIBLE piece of code, unfit for any department but what it DOES is keep LOOPING WHILE the magic word “QUIT” is NOT typed in.  It’s just an example of how it COULD be used not how it SHOULD be used.  (Thus why am an ITPro and not a Developer)

A good example of the Do UNTIL loop would be

DO { ALL OF THIS STUFF THAT’S IMPORTANT } UNTIL ( SOMETHING –eq SOMETHINGELSE )

To see how it really works…

DO {

WRITE-HOST ‘Enter a Name now!’
$SOMENAME=READ-HOST
#
# YOU KNOW AT THIS POINT I SHOULD PUT IN SOMETHING EVEN
# MORE IMPRESSIVE THAN THAT LAST SCRIPT WHICH
# HAD ABSOLUTELY NOTHING TO IMPRESS WITH
# BUT YOU GET THE IDEA

} UNTIL ( $SOMENAME –eq ‘NotMe’ )

See?  Again not the best Example of how you SHOULD do it but hopefully an example basic enough to grasp on.

We’ll poke a bit more into other things next time. Maybe something fun like Quantum Mechanics.

Ah, the back row just fainted dead again…

Cheers all

Sean
The Energized Tech

Leave a Reply