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.

2 Answers 2

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
) 
} 
Sign up to request clarification or add additional context in comments.

1 Comment

This would work though it would mean adding while loop for each and every input.
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

3 Comments

This would require adding loop for each and every one of the inputs.
@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).
Thanks! I would try using this one, since it makes more sense

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.