Author Posts

November 12, 2017 at 7:22 pm


I want to get a random number between 1 to 10. However, I want to exclude numbers the lets say 2 and 8. I want a variable that has numbers to exclude. How can I do this? Thanks

November 12, 2017 at 8:44 pm

There is no exclude option for that cmdlet.

As per the built-in PoSH help files, you can take this approach...

# Example 5: Get a random integer from an array
Get-Random -InputObject 1,3,4,5,6,7,9,10

# Or for your ask

$MyNumbers = 1,3,4,5,6,7,9,10
Get-Random -InputObject $MyNumbers

November 12, 2017 at 10:52 pm

This is overkill for the scope you're wanting but it can be useful in more dynamic environments or where the range is much larger and there are more exclusions.

[System.Collections.ArrayList]$NumRange = @()
[System.Collections.ArrayList]$Exclusions = @()

# Define and add values to the NumRange ArrayList
$range = 1..10
$range | ForEach-Object { $NumRange.Add($_) }

# Define and add values to the Exclusions ArrayList
$exclRange = 2,8
$exclRange | ForEach-Object { $Exclusions.Add($_) }

foreach ($ex in $Exclusions) {

Then pipe $NumRange to Get-Random:

$NumRange | Get-Random

This will provide Get-Random the range you're wanting without the numbers you want excluded.

November 13, 2017 at 12:12 am

Thank You. I wanted to get a range of AD phone numbers with extensions and have powershell get a random extension not in use. Is there another way to have powershell automatically assign a user a number not in use?

November 13, 2017 at 12:22 am

If you don't need to re-use "free" numbers you could simply determine the highest and add one. 😉