0

I have a script which takes lots of input from user. I need to validate those inputs. The issue I am currently facing is that if one of the input fails validation, the user should be prompted to re-enter only that particular input and rest all valid inputs should remain as is

Sample Code :

    Function Validate 
{ 
Param( 
[Parameter(Mandatory=$true)] 
[ValidateNotNullOrEmpty()] 
[ValidateLength(3,5)] 
[String[]]$Value 
) 
} 
$Value = Read-Host "Please enter a value" 
Validate $Value 
Write-Host $value 
$Test = Read-Host "Enter Another value" 
Write-Host $Test

Here when validation fails for $Value it throws exception and moves to take second input.

NewUser
  • 1
  • 1

2 Answers2

1

You can add it directly into the parameter using ValidateScript

Function Validate 
{ 
Param( 
[Parameter(Mandatory=$true)] 
[ValidateScript({
while ((Read-Host "Please enter a value") -ne "SomeValue") {
Write-Host "Incorrect value... Try again"
Read-Host "Please enter a value"
}})]
[string]
$Value
) 
} 
Avshalom
  • 8,657
  • 1
  • 25
  • 43
0

You might use this PowerShell Try/Catch and Retry technique to do this like:

function Get-ValidatedInput {
    function Validate { 
        Param( 
            [Parameter(Mandatory=$true)] 
            [ValidateNotNullOrEmpty()] 
            [ValidateLength(3,5)] 
            [String]$Value
        )
        $Value
    }
    $Value = $Null
    do {
        Try {
            $Value = Validate (Read-Host 'Please enter a value')
        }
        Catch {
            Write-Warning 'Incorrect value entered, please reenter a value'
        }
    } while ($Value -isnot [String])
    $Value
}
$Value = Get-ValidatedInput
$Test = Get-ValidatedInput
iRon
  • 20,463
  • 10
  • 53
  • 79
  • This would require adding loop for each and every one of the inputs. – NewUser Dec 14 '22 at 10:59
  • @NewUser, isn't that where you ask for: *the user should be prompted to re-enter*? Anyways, you might put everything in a main `Get-ValidatedInput` function so that you might reuse it (see my update). – iRon Dec 14 '22 at 11:12
  • Thanks! I would try using this one, since it makes more sense – NewUser Dec 14 '22 at 11:28