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.
The abs() function is used to get the absolute (positive) value of a given number. The argument may be an integer or a floating point number. If the argument is a complex number, its magnitude is returned.
If the Integer is greater than zero then it is a positive integer. If the number is less than zero then it is a negative integer. If the number is equal to zero then it is neither negative nor positive.
Use abs(x) Python native function. EDIT: if you want to raise an error, instead, I would make use of assertions (example taken from here: x = 0 assert x > 0, 'Only positive numbers are allowed' print('x is a positive number.
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
Since PowerShell 6.1.0 you kan use ValidateRangeKind to initialize the attribute:
[Parameter(Mandatory = $false)]
[ValidateRange("Positive")]
[Int] $Number = 5
ValidateRange validation attribute
The ValidateRange attribute specifies a numeric range or a ValidateRangeKind enum value for each parameter or variable value. PowerShell generates an error if any value is outside that range.
The ValidateRangeKind enum allows for the following values:
- Positive - A number greater than zero.
- Negative - A number less than zero.
- NonPositive - A number less than or equal to zero.
- NonNegative - A number greater than or equal to zero.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With