Home > Mobile >  Powershell : Reprompt user for input if validation fails
Powershell : Reprompt user for input if validation fails

Time:12-14

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.

CodePudding user response:

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
) 
} 

CodePudding user response:

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
  • Related