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

 
Participant
1 year ago.

  • Author
    Posts
  • #84044

    Participant
    Points: 0
    Rank: Member

    Hello,

    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

    Participant
    Points: 208
    Helping Hand
    Rank: Participant

    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

    Participant
    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) {
        $NumRange.RemoveAt($NumRange.IndexOf($ex))
    }
    

    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

    Participant
    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

      Participant
      Points: 144
      Helping Hand
      Rank: Participant

      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.