Simple Random Number Demonstration Script
I was delivering my session today at the Alpharetta (Atlanta) PFE Technology Day, and needed to come up with a good way to give away a free book to the class. Right before class I threw a little script together to use the random number capabilities of PowerShell. The script is below:
$rand = new-object random $ofstudents = 50 for ($i=1;$i -le 100;$i++) {[math]::Round($rand.NextDouble()*$ofstudents,0)} start-sleep -seconds 2 cls write-host "And the Winner Is!!!!!" start-sleep -seconds 5 (new-object -comobject wscript.shell).Popup($([math]::Round($rand.NextDouble()*$ofstudents,0))) |
The key piece here is the use of the object type "random" which is system.random and can be found in the MSDN .Net documentation (https://msdn.microsoft.com/en-us/library/system.random.aspx). Once the object is created, you use methods to actually get the numbers. I have always like getting a decimal between 0 and 1 so that I can simply multiply it times the range I want to generate any number. I am using the .NextDouble() method to get my numbers (https://msdn.microsoft.com/en-us/library/system.random.nextdouble.aspx). In this case I multiply it times the number of students and round off the number. I do this 100 times and the 101 first random number is the winner.
I took this opportunity as well to use the old wscript.shell .Popup() method to created a little popup box for the winner display. Like most of my posts, this is not rocket science here, but it was a fun little way to demo a simple PowerShell script that uses random numbers and an old COM object while giving away some SWAG...yes it was Ed Wilson's PowerShell Step-By-Step book :)
This posting is provided "AS IS" with no warranties, and confers no rights. Use of included script samples are subject to the terms specified at https://www.microsoft.com/info/cpyright.htm.