Using a Counter Variable in a PowerShell Workflow Foreach -Parallel Loop

As I'm sure most of my blog readers are aware, I competed in the advanced track of the Scripting Games this year and ended up doing quite well. Two first place finishes and three second places finishes with the official judges and four first place crowd score finishes. I also ended up being the overall winner of the advanced track.

A few days ago someone on twitter asked me as the winner of the Scripting Games advanced track, what I would do with it? I plan to use it as a tool. I'll continue doing the same thing I've been doing of learning more and trying to spread the word about PowerShell to others as well as sharing my knowledge of what I learn. Maybe as a Scripting Games winner, a few more people will listen.

Today I'll start the first of many blogs to come in a series that shares information about what I learned during the Scripting Games. During event six, one of the goals was to name servers as SERVER1, SERVER2, etc. I started out doing something like this in a foreach loop:

1foreach ($_ in 1..10){
2    $i++
3    $a = "SERVER"
4    "$a$i"
5}

workflow-counter1.png

Then I ended up using a workflow with foreach -parallel and that didn't work out so well:

1workflow test {
2    foreach -parallel ($_ in 1..10){
3        $i++
4        $a = "SERVER"
5        "$a$i"
6    }
7}
8test

workflow-counter2.png

Here's what I discovered was the solution to return the desired results in a workflow foreach -parallel loop:

1workflow test {
2    foreach -parallel ($_ in 1..10){
3        $workflow:i++
4        $a = "SERVER"
5        "$a$i"
6    }
7}
8test

workflow-counter3.png

I ended up not using this particular method of naming the servers, but this was something that wasn't easy to figure out and there isn't much documentation in books or on the Internet about this so I thought it was worth sharing and in six months when I need to do something like this again, I can search my blog to figure out how I did it.

Update:

I received a tip from Jeff Hicks about not being able to count on the results from the workflow being sequential.

µ