Exlude Numbers from get-random

Welcome Forums General PowerShell Q&A Exlude Numbers from get-random

This topic contains 4 replies, has 4 voices, and was last updated by

1 year, 3 months ago.

  • Author
  • #84044

    Points: 0
    Rank: Member


    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

  • #84046

    Points: 785
    Helping Hand
    Rank: Major Contributor

    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

  • #84058

    Points: 0
    Rank: Member

    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.

  • #84061

    Points: 0
    Rank: Member

    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?

    • #84068

      Points: 740
      Helping Hand
      Rank: Major Contributor

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

The topic ‘Exlude Numbers from get-random’ is closed to new replies.

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort