Try catch throw question

Greetings experts!

Can’t figure out how to return to reloop through the try catch throw when a incorrect value is entered. Currently upon entering an incorrect value the validation test displays an error message. A correct works with no issues.

function FOO
{


[CmdletBinding()]

param(

    [Parameter(Mandatory,HelpMessage="Enter a Datacenter Name")]

    [ValidateScript({

        try{

            Get-DataCenter -Name $_ -ErrorAction Stop
            
        }

        catch{

            throw "Datacenter $_ not found. Please enter a valid Datacenter Name."
            
        }
    
    })]

    [String[]]

    $DCChoice

    )


   $DCChoice 

}

Thank you in advance for your inputs.

Norm

Hello Norm,

In the validation script, you don’t need to catch the error, if it is not validated as per the logic then the script itself throws an error like this…

[pre]FOO : Cannot validate argument on parameter 'DCChoice'[/pre]
Thank you.
 

Hello Kiran,
Thank you for your reply. As usual not making myself clear if I enter the following:
10:31AM D:\PowerShell_Test\powercli> FOO -DCChoice xxxx wvhq
FOO : Cannot validate argument on parameter ‘DCChoice’. Datacenter 12/23/2019 10:32:04 AM Get-Datacenter Datacenter with name ‘xxxx’ was not found using the specified
filter(s). not found. Please enter a valid Datacenter Name.
At line:1 char:16

  • FOO -DCChoice xxxx wvhq
  •            ~~~~
    
    • CategoryInfo : InvalidData: (:slight_smile: [FOO], ParameterBindingValidationException
    • FullyQualifiedErrorId : ParameterArgumentValidationError,FOO

Would like to have the validation test restart giving the user another opportunity to enter a correct value without having to restart the function. Hope this makes some sense. Maybe what I’m asking for is not possible

Norm

If you want a re-prompt, that is normally done outside the function like so:

$svcs = Get-Service | Select-Object -ExpandProperty Name

do {
    $prompt = (Read-Host -Prompt 'Enter the name of the service').Trim()

    if (-not ($svcs -contains $prompt)) {
        '{0} is not a valid service' -f $prompt
    }
}
while (-not ($svcs -contains $prompt))

Get-Service -Name $prompt

Rob,
Don’t understand how to incorporate your response into the function, are you saying I have to somehow call the function in the try catch?

Thank you for your input

Norm

Normally I don’t do the retry within the function, I ask the function to return a status message as a hashtable and performs the retry in the script.
Based on your scenario, probably I would try something like this.

[PRE]
function FOO
{
[CmdletBinding()]
param(

[Parameter(Mandatory,HelpMessage="Enter a Datacenter Name")]
[String]$DCChoice

)

$exitFlag = $False

Do
{
    Try
    {
        $DC = Get-DataCenter -Name $DCChoice -ErrorAction Stop
        $exitFlag = $true
    }
    Catch
    {
        $DC = $null
        $title = "wrong DC Name"
        $prompt = "$DCChoice was wrong, Would you like to [A]bort or [R]etry?"
        $choices = @('&Abort','&Retry')
        $choice = $host.ui.PromptForChoice($title,$prompt,$choices,0)
        If($choice -eq 0){$exitFlag = $true}

    }
}Until($exitFlag)

If([String]::IsNullOrEmpty($DC))
{
    Return 'NotProcessed'
}

}
[/PRE]

Instead of using the validate script you can use dynamic validate set, get all the valid values and use them in the validate set, please refer to the link below…

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_functions_advanced_parameters?view=powershell-6#dynamic-validateset-values

Hello rejikodiyil

What you have is what I’m except the RETRY doesn’t work when I press retry nothing happens the abort option works perfectly. DO you have sometime to help me with the retry option,is there a way to return to start over again allowing the user to retry entering the correct datacenter?

Thank you for your input

Norm