This is my first script so don\'t beat me up to bad!
I\'m working on a script that creates a network directory & AD group based on user input. The following is w
As @briantist already pointed out, validation functions were made for a different purpose (parameter validation). You have a different scenario, since you want to keep prompting the user until a valid value is entered. Validation functions just don't work well in this scenario for a number of reasons:
I would probably put the input/validation loop in a function and use numeric comparisons instead of checking the length of a string, since you're asking the user to input numbers anyway.
function Get-Number {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true)]
[string]$Prompt,
[Parameter(Mandatory=$false)]
[int]$Min = 0,
[Parameter(Mandatory=$false)]
[int]$Max = 9999
)
# prevent infinite loop due to impossible condition
if ($Min -gt $Max) { throw 'Min cannot be greater than max.' }
$ErrorActionPreference = 'SilentlyContinue'
do {
$num = Read-Host -Prompt $Prompt
$valid = $Min -le $num -and $Max -ge $num
if (-not $valid) { Write-Host "Invalid value: $num" }
} until ($valid)
return [int]$num
}
$Division = Get-Number -Prompt 'Please enter the TWO digit division number' -Min 10 -Max 99
$Matter = Get-Number -Prompt 'Please enter the FOUR digit matter number' -Min 1000 -Max 9999
$Client = Get-Number -Prompt 'Please enter the FOUR digit client number' -Min 1000 -Max 9999