Thursday, June 17, 2010

Powershell Quick Hit - Doing it X times

I learned a cool and easy trick today for running a block of code a defined number of times.

It started with a simple commandlet called get-random, which, as you might expect, is a random number generator. You can feed it -min and -max values.

So "get-random -min 1 -max 10" generates a random number between 1 and 10. I wondered how I could do that 20 times.

There's a "for" looping contruct that works like this:

FOR ($i = starting value; $i -le X (less than or equal to) (max value); $i++ (increment by 1)
{do code here}

PS>for ($i = 0; $i -le 10; $i++) {$i}
0
1
2
3
4
5
6
7
8
9
10

Combining those 2 concepts together works fine:

for ($i = 0; $i -lt 20; $i++) {Get-Random get-random -min 1 -max 10}
generates 20 random numbers between 1 and 10.

But here's the cool Powershell quick hit - look how easy Powershell makes doing this using forEach and a range (1..20)

PS>1..20 | ForEach {get-random -min 1 -max 10}
2
5
7
8
4
2
7
4
9
7
1
7
9
2
1
9
6
2
4
4

1 comment:

  1. One odd thing that I noticed, the MIN value (I used 1) includes 1, but the MAX value (10) is NOT included.

    ReplyDelete

Are you in favor of irradating food?