Sunday, July 15, 2012

Easy PowerShell 2: Foreach


Just as it sounds, for each item in an array (or collection) of items, do something.

Foreach($item in $arrayOfItems)
{
                DoSomething $item
}

In our baseball example, we might to deal with all the players on team.  To do this we can create $team variable that is a special kind of variable, called an array.  An array is essentially a set of like objects or variables.

So we might have $team as an array baseball players.

Let’s say we have a win’s variable as a NoteProperty member of our baseball player object.  We could then update all the players on a team by running a foreach loop against an array that contains all of our baseball players, and within that loop update the value of the wins variable.  We could even write our loop in a way that makes it easy to ready, a la:  foreach($player in $team){$player.wins += 1}

Loops like this are what us deal with bulk processes like PST captures.  “Get-content filename” really just creates an array that gets handed off to the next cmdlet in the pipeline.

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.