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

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.

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

In Powershell 5

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

Tags:

Int

Powershell