I want to do some basic validation on a user input in PowerShell to ensure a user can only enter a whole integer and does not enter -7 for example. I am not sure how this is done and would appreciate a pointer.
[parameter(Mandatory=$false)][int]$number
If a user enters -$number
this will be accepted. I want it to reject this type of input.
You can use ValidateRange
for the parameter:
[parameter(Mandatory=$false)]
[ValidateRange(1, [int]::MaxValue)]
[int] $number
From the documentation:
ValidateRange Validation Attribute
The ValidateRange attribute specifies a numeric range for each parameter or variable value. Windows PowerShell generates an error if any value is outside that range. In the following example, the value of the Attempts parameter must be between 0 and 10.
Param ( [parameter(Mandatory=$true)] [ValidateRange(0,10)] [Int] $Attempts )
In the following example, the value of the variable $number must be between 0 and 10.
[Int32][ValidateRange(0,10)]$number = 5
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments