Try catch throw question

Welcome Forums General PowerShell Q&A Try catch throw question

Viewing 7 reply threads
  • Author
    Posts
    • #194972
      Participant
      Topics: 22
      Replies: 58
      Points: 178
      Rank: Participant

      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

    • #194978
      Moderator
      Topics: 3
      Replies: 169
      Points: 891
      Helping Hand
      Rank: Major Contributor

      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...

      FOO : Cannot validate argument on parameter 'DCChoice'
      Thank you.

       

    • #194981
      Participant
      Topics: 22
      Replies: 58
      Points: 178
      Rank: Participant

      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: (:) [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

    • #195002
      Participant
      Topics: 10
      Replies: 1381
      Points: 1,509
      Helping Hand
      Rank: Community Hero

      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
      
    • #195005
      Participant
      Topics: 22
      Replies: 58
      Points: 178
      Rank: Participant

      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

    • #195023
      Participant
      Topics: 0
      Replies: 28
      Points: 142
      Helping Hand
      Rank: Participant

      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.

      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'
          }
      }
      
    • #195026
      Moderator
      Topics: 3
      Replies: 169
      Points: 891
      Helping Hand
      Rank: Major Contributor

      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

    • #195272
      Participant
      Topics: 22
      Replies: 58
      Points: 178
      Rank: Participant

      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

Viewing 7 reply threads
  • You must be logged in to reply to this topic.