Try / Catch Help

This topic contains 3 replies, has 3 voices, and was last updated by  Joel Sallow 1 month, 4 weeks ago.

  • Author
    Posts
  • #97236

    Rob Marshall
    Participant

    How do you use a Try/Catch loop that if an error is found, it repeats the "Try" portion of the loop again???

    I.E
    Try
    {
    Ask for input
    }
    Catch
    {
    Input not valid
    *** Then return back to ask for input in the Try section ***
    }

  • #97238

    Don Jones
    Keymaster

    You build a loop. But, before we go there, a Try/Catch isn't really the right way to check input validity.

    $valid = $false
    Do {
     # Get $the_input
     If ($the_input -is [string]) {
      $valid = $true
     }
    } Until ($valid)
    
  • #97241

    Rob Marshall
    Participant

    Much better solution, Thanks!!!

  • #97242

    Joel Sallow
    Participant

    A much more reliable approach for input validation is simply to declare parameters for your script, or your functions.

    param(
        [Parameter(Position = 0, Mandatory)]
        [ValidateSet('One', 'Two', 'Three')]
        [string]
        $Test
    )
    

    Here, the $Test parameter must always be specified when calling the script or function. If it is not provided, PS will automatically prompt for the value. It will only accept one of the provided values as its input, and it will only accept string input (no weird GUIDs, XML documents, or random file references, etc.)

    If any other input is provided, PS will display a red error and stop, allowing the user to call the function or script again with different parameters.

    Trying to validate your own input should generally only take place in GUIs — for CLI, parameter validation is more than sufficient for just about anything you'll need.

    Check out Get-Help about_Advanced_Parameters for more. 🙂

You must be logged in to reply to this topic.