Monday, July 30, 2012

Easy PowerShell 4: While


$thing = “slimey”
While($thing -eq “slimey”)
{
                DoSomething
}

This stayed on the board an extra day because someone decided to make a change which needed to undone.

This example is a “while” loop:  a construct which combines loops and conditionals.  In this instance, the loop will run so long as the $thing variable is equal to “slimey”.  This introduces a risk:  if $thing never gets changed, the loop will continue infinitely.

The change someone made was obviously intended to avoid this.  It introduced concepts I’m not ready to cover yet, but I’ll do so.  Unfortunately, since the definition of the doSomething function isn’t available, we don’t know if that was appropriate.  It is possible that a function you call will access external data, and use that to make decision regarding the modification of other variables.  Perhaps the DoSomething function was checking a webservice for the current temperature and humidity, and using that to determine whether the porch at home will be slippery, and if so, change the value of $thing to “slimey”.

The while loop is incredibly powerful.  As always, power is dangerous and should be wielded wisely.

In our baseball example we can have a variable on a team object for $atBat.  Our while loop might then be

$teamObj.atBat = $true

While($teamObj.atBat -eq $true)
{
                $batter = read-host “who is up”
                $pitch = read-host “ball, strike, hit, balk, hit-batter, whateverelsewewant
                If($pitch -like “strike”)
                {
                                $atBat.strikes += 1
                }
                If($atBat.strikes -eq 3)
{
                                $outs +=1
}
                If($outs -eq 3)
                                {
                                $teamObj.atBat = $false
}
}

In this example we have all sorts of stuff going on, but the gist is that we ask what happened until someone gets out, then we add an out, and when we get 3 outs we end the loop.

Obviously this would be much more complex if we wanted to really track a baseball game.

It is not always appropriate to pre-set a limit on our loops.  Sometimes the number of repetitions is entirely dependent on what happens within the loop.

No comments:

Post a Comment

I look forward to your feedback and questions. The rules for commenting are simple. No personal attacks against other commenters. No threats.