Friday, January 15, 2016

PowerShell’s Get-Random Cmdlet–a curiosity

I’ve been working on a new set of Introduction to PowerShell courses for a new client – and in doing do, I’m recycling bits of the courseware I’ve developed for my  my own PowerShell training courses. I’ve been running these for 10 years now and have an awful lot of  PowerShell decks on file!

I was looking at an example that was actually based on Version 2 of PowerShell. The example used the PSCX extensions’ Get-Random cmdlet. Well – in those days the PowerShell Community Extensions did contain such a cmdlet - the latest versions of PSCX have sensibly deprecatexd it in favor of the cmdlet built into PowerShell. The original PSCX cmdlet generated a random number between 0 and 1. So to generate a random number between 0 and 4, you could do this (again with the PSCX cmdlet) you could use: (Get-Random)  * 4. The smallest number generated would be .(and lots of zeros)1, and the largest .999999 etc. Multiply those by 4, and using interger rounding,  you have the random number between 0 and 4.

Well – to convert this to the built in cmdlet would, I thought, be easy.

Get-Random –Minimum 0 –Maximum 4

Except it did not seem to work right. If I ran this 100000 times, I only ever ended up with numbers zero through three. NO four. Then I looked closely at the documentation. Get-Random’s –Minimum specifies the smallest random number to be generated. The –Maximum parameter specifes a number such that the random number generated will be LESS than the maximum. SO the random number will be Greater or equal to zero, and less than 4.

So to create a random number greater than or equal to zero and less than or equal to four:

Get-Random –Minimum 0 –Maximum 5

Just goes to show, sometimes reading the documentation is useful.

No comments: