Sunday, July 22, 2012

Easy PowerShell 3: If-Else and Conditionals


Today's snippet introduced conditional statements with the classic if-else construct.

If($var -eq $condition)
{
                DoSomething
}
Else
{
                DoTheOtherThing
}

There are 3 important pieces to the snippet above.  First is the if statement.  Exactly as it sounds, if a condition is true, perform the action listed within the curly braces that follow.  In this particular instances if the variable $var is equal to the variable $condition, run the function named DoSomething.  Next is the -eq operator, which is one of many ways of evaluating conditions.  Some other common operators are -like (string comparison), -gt (greater than), -lt (less than), -match (regular expression match), and -neq (not equal).  The third important piece is the else statement.  This tells PowerShell to perform the actions in the curly braces that follow in the event that the if condition is not true.  Else is optional in the if construct, so you can have an if statement by its self, but you can’t have an else statement by its self.

So, back to our baseball example.  Once we get out of little league, there are usually more players on the roster than actually play in any particular game.  Yesterday we dealt with adding wins to all the players on a team.  You may want to only add wins (and games played) when the player actually played.  So if we have a variable in our baseball player object we set every game to track whether or not the player got to play, we can use this to control our foreach actions.

$baseballPlayer | add-member -memberType NoteProperty -name playedTonight -value $false

Now we can update our loop to the following

Foreach($player in $team)
{
                If($playedTonight -eq $true)
                {
                                $gamesPlayed += 1
$wins += 1
                }
}

Obviously, as you’re sitting on the sofa, laptop on your lap, you’ll have to find each player in the $team array and update their $playedTonight variable appropriately.  We’ll deal with that later.

Conditional logic is probably the most powerfull element of any programming language.  It’s what allows the computer to make decisions rather than just blindly performing actions.

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.