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

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

ReplyDelete