a_m_2016
a_m_2016

Reputation: 275

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.

Upvotes: 22

Views: 30591

Answers (4)

iRon
iRon

Reputation: 23663

If you want to include the zero, you might simply use the [uint] or [ulong]types (which also give you a larger range of positive numbers):

[parameter(Mandatory=$false)][uint]$number

Upvotes: 2

inorangestylee
inorangestylee

Reputation: 41

In Powershell 5

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

Upvotes: 4

mhu
mhu

Reputation: 18051

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.

Upvotes: 11

Joey
Joey

Reputation: 354566

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

Upvotes: 35

Related Questions