Thursday, September 17, 2009

Random number generator

PowerShell does not have a native randomizer, but it's a good thing that PowerShell does rely on .NET.  .NET, however, can be tricky to deal with some times.  In this case, it is not.  System.Random is a very easy to use class.  We simply ask for the Next number.

ONELINER

0..9) | % { Write-Host (New-Object System.Random).next(10) ; Start-Sleep -Milliseconds 1 }


PEICE BY PEICE
(0..9)
writes back through the pipe 0-9 sequentially

% { write-host (new-object System.Random).next(10)
Since we're not passing $_ to anything the numbers 0-9 dissappear, but allow us to continue for each number.  a new .NET object is created for the System.Random class.  Calling the .next method and passing it an int32, we will be returned a  nonnegative random number less than the specified maximum; in this case, that would be 10.

; Start-Sleep -Milliseconds 1
; essentially is a way to seperate individual commands on a single line.  Start-Sleep does just that.  It causes PoSh to sleep for the given count in milliseconds.  This can also be specified in seconds.  Most computers are so quick now that without this momentary - although unnoticeable - pause System.Random will not be able to create a new number.  The algorythem used is based on the current date and time counted to the nearest millisecond.

NOTE
This will generate 10 random numbers between 1 & 10.  To create more or fewer change the initial (0..9) to your specified range: ex (4..6) would generate 3 numbers by passing 4, then 5, then  to the host.  .next(10) will specify a number UP TO (not including) 10.  A specific range can be used for generation by seperating the numbers with a comma:ex .next(16,38) would generate a number between, but not including 16 & 38.

ALIASES
% = ForEach-Object

0 comments: