How to limit int up to 5 numbers?

Hi all

how can I limit this

Powershell

[int]$EmployeeNumber = Read-Host “Enter Employee Number”

so can we use just 5 numbers and if enter more than 5 it will give a message?
try that

$EmpNumOK = $false
While (-not $EmpNumOK) {
 $EmployeeNumber = Read-Host "Enter Employee Number"
 If ( ($EmployeeNumber.length) -le 5) {
   $EmpNumOK = $true
   $EmployeeNumber = [int] $EmployeeNumber }
 Else {
   Write-Host "Length of $($EmployeeNumber.length) invalid"
 }
}

but is not limit to any number
any help please?

So you don’t like my suggestion to create an employee number automatically? :wink:

If I remember right we’ve already had this issue. The most professional way would be to use a function with advanced parameters and use their validation processes.

If 32767 would be enough you could use this:

function New-EmployeeNumber {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true,
            HelpMessage = "Please enter an integer between 1 and 32767")]
        [int16]
        $EmployeeNumber
    )    
    begin {
    }
    process {
        "Do whatever you need to do with '$($EmployeeNumber)'"
    }
    end {
    }
}

If you really need more than that you could use an [int32] with a validate range like this:

function New-EmployeeNumber {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true,
            HelpMessage = "Please enter an integer between 1 and 99999")]
        [ValidateRange(1, 99999)]
        [int32]
        $EmployeeNumber
    )    
    begin {
    }
    process {
        "Do whatever you need to do with '$($EmployeeNumber)'"
    }
    end {
    }
}

Please (re-)read the help topic for about_Functions_Advanced_Parameters

BTW: What’s wrong with the automatic approach? I still think it would be less error prone and faster.

Edit:
Another approach would be something like this:

[int]$Choice = 0
do {
    try {
        [int]$Choice = Read-Host 'Please enter a number between 1 and 99999'  -ErrorAction Stop
    }
    catch {
        Write-Warning 'Please enter a number between 1 and 99999'
    } 
}
until ($Choice -gt 0 -and $Choice -le 99999 )