Search code examples
powershellrandomminimum

Get-Random returning exclusively the minimum value


I've been trying to get Get-Random to choose between 0 and 1 so I can emulate the equivalent of a coin flip, but even when I place it in an infinite while loop it exclusively returns 0, Example code:

$test = Get-Random -Maximum 1 -Minimum 0
Write-Host $test

Only difference to my script is that this is in a function and it's being called in an infinite while loop, although even cutting out the middleman of the function doesn't work so it's definitely something wrong with my Get-Random. Hope that helps, and to keep in mind I'm still learning this stuff haha.


Solution

  • Get-Random -Maximum 1 -Minimum 0
    

    returns a random integer greater than or equal to 0 and less than 1, so it will always return 0.

    So, to get 0 or 1, the maximum would need to be 2

    Get-Random -Minimum 0 -Maximum 2
    

    Alternatively, specify or pipe an array of alternatives to be randomly selected from

    Get-Random 0,1
    0,1 | Get-Random