PowerTip: Use PowerShell to Simplify Working with Random Numbers


Summary: Learn about using Windows PowerShell to generate random numbers.

Hey, Scripting Guy! Question How can I generate a random number?

Hey, Scripting Guy! Answer 

a. Use the Get-Random cmdlet.

b. Use the System.Random .NET Framework class, and call the next() method:

([random]5).next()

Hey, Scripting Guy! Question How can I generate a random number between the values of 1 and 10?

 Hey, Scripting Guy! Answer

a. Use the System.Random .NET Framework class, and call the next() method:

([random]5).next(“1”,”10”)

b. Use the Get-Random cmdlet:

Get-Random -Maximum 10 -Minimum 1

Comments (4)

  1. jrv says:

    I like that idea.  A predictable random number.  That has great implecations for gaming strategies in Las Vegas.  Just think.  We could set it up so the dice always land in an exact set of 'shows'.  

    This could be a whole new area of mathematics.  Non-random randomness.

    😉

  2. Walid Toumi says:

    hi

    with date:

    $date1 = get-date

    $date2 = (Get-Date).adddays(-2)

    $date2.adddays((new-object random).next(([TimeSpan]($date1-$date2)).Days + 1))

  3. ihunger says:

    Can you seed the random number generator so you get the same sequence of random numbers each time? It's useful for making repeatable tests.

  4. Gregg5 says:

    hello this probably has already been answered but I cannot find it. Using for example Get-Random -InputObject 2,44,55,6 I can get a random number from the list(for example 55). What did not see was how to either eliminate 55 from the list or keep from
    being chosen again at some other time. I came up with the scheme such as storing the number, in this case 55, in an array so I could compare it to a new random number to make sure they are not the same and if so run Get-Random again. I suspect there is better
    way to do this.