Get a random decimal number between 0 and 1 in PowerShell

Get-Random -Maximum ([Double]1)

How does this work? The Get-Random cmdlet returns a Double (that’s a decimal number) when the Maximum parameter is a Double. If we just wrote -Maximum 1, then PowerShell would interpret the 1 as an integer. So we cast the 1 as a Double by writing it as [Double]1. Since [Double]1 is not a simple value or variable, PowerShell will misinterpret this as a parameter. So we wrap if in parentheses to get: ([Double]1). This grouping tells PowerShell to evaluate it first, then use that result as the parameter.

Minimum defaults to 0, so we don’t need to specify it.

How this helps!

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *