ValidateLength Powershell

后端 未结 3 1524
渐次进展
渐次进展 2021-01-20 18:28

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

3条回答
  •  庸人自扰
    2021-01-20 18:48

    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:

    • they throw an error instead of returning a boolean value, which is fine for a function call, but not for validating a value.
    • they don't repeat, so you need additional code anyway,
    • their parameters can't be variables.

    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
    

提交回复
热议问题