Skip to content

Fun with get-Random

2011/06/25

get-random is function for creating random values. The seed is a random start number for the algorithm. The seed is an int32 value. Okay where do we get a “random” seed ?

We can use the current time. The milliseconds from get-date can be used. By multiplying 2 of this values you get a range from 0 to 1000000 for the seed. 2 sequential calls of get-date give values that depend on “what is happening on the machine”. So the multiplication of them should put additional “randomness” to the seed.

The seed is (get-date).Milliseconds *  (get-date).Milliseconds

 

The seed can be used to reproduce the same sequence of random numbers, wich can be useful for creating test data.

______________________________________________________________________________________
PS C:\> Get-Random -SetSeed 3 ; Get-Random ;Get-Random
630327709
1498044246
1857544709

__________________________________________________________________________________________________________________________________________________
PS C:\> Get-Random -SetSeed 3 ; Get-Random ;Get-Random
630327709
1498044246
1857544709

__________________________________________________________________________________________________________________________________________________
PS C:\> Get-Random -SetSeed 3 ; Get-Random ;Get-Random
630327709
1498044246
1857544709

get-random can also pick random objects from a list you feed to it:

PS C:\> (“blue”, “red”, “yellow”, “green”, “brown”, “black”, “white”) | get-random
yellow

 

The “reproduction” by setting the seed also works:

PS C:\> $d = get-random -setseed 4 ;1..5| %{(“blue”, “red”, “yellow”, “green”, “brown”, “black”, “white”) | get-random  }
brown
yellow
red
yellow
green

__________________________________________________________________________________________________________________________________________________
PS C:\> $d = get-random -setseed 4 ;1..5| %{(“blue”, “red”, “yellow”, “green”, “brown”, “black”, “white”) | get-random  }
brown
yellow
red
yellow
green
You can also pick more than one value from the list by using the “count” parameter. If you choose the count greater than the number of elements in the list, you get only “all list elements”. That is why I’d assume that you get always the count different random elements.

Advertisements

From → basics, powershell

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

%d bloggers like this: