PSTip: Get-Random


The first prize of the famous lottery Sportka (Czech Republic)  is currently about 124000 €.

Sportka allows us to select 6 numbers from 49 (array of numbers 1-49) on the lottery ticket.

I wanted to bet just for fun. So why not to generate 6 numbers by PowerShell and Get-Random ;-).

We can use for example:

PS C:\> Get-Random -InputObject (1..49) -Count 6 
19
20
25
6
48
27

PS C:\> 1..49 | Get-Random -Count 6
2
22
48
20
36
9

PS C:\> 1..5 | % { (1..49 | Get-Random -Count 6) -join (",") }
35,1,37,6,31,4
7,10,47,3,37,33
28,43,44,42,21,29
31,49,7,17,14,33
30,20,2,43,29,45

And what about the following?

PS C:\> 1..6 | % { Get-Random -Minimum 1 -Maximum 50 }
48
42
45
40
30
23

It is not good idea because we can get the same numbers. It is improbable at this point but look at this:

PS C:\> 1..6 | % { Get-Random -Minimum 1 -Maximum 6 }
2
2
3
5
5
3

Of course that we can use something like that:

PS C:\> do { if( ($num=(Get-Random -Minimum 1 -Maximum 7) ) -notin $nums ){ [int[]]$nums+=$num } } while ( $nums.count -lt 6 ) $nums
3
4
1
5
6
2

But why to use that horrible command when 1..6 | Get-Random -Count 6 cannot display duplicates :-D.

By the way, the syntax does not support -Count and -Minimum or -Maximum parameters together.

  • Get-Random [[-Maximum] <Object>] [-Minimum <Object>] [-SetSeed <Int32>] [<CommonParameters>]
  • Get-Random [-InputObject] <Object[]> [-Count <Int32>] [-SetSeed <Int32>] [<CommonParameters>]

Feel free to use Get-Random also in the context of:

  • Get-Mailbox | Get-Random
  • Get-Service | Get-Random
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s