'How can ensure that a function only accepts a positive integer?

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.



Solution 1:[1]

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

Solution 2:[2]

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.

Solution 3:[3]

In Powershell 5

[Parameter(Mandatory = $false)]
[ValidateScript({$_ -gt 0})]
[Int] $Number = 5

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Matt
Solution 2 Community
Solution 3 inorangestylee