Capturing ValidateSet errors

Welcome Forums General PowerShell Q&A Capturing ValidateSet errors

This topic contains 1 reply, has 2 voices, and was last updated by

 
Moderator
3 weeks, 5 days ago.

  • Author
    Posts
  • #146310

    Participant
    Points: 17
    Rank: Member

    I have the following example:

    $ErrorActionPreference = 'Stop'
    
    Function Get-Example {
    
             [CmdletBinding()]
    
             Param(
    
                   [Parameter(Mandatory = $True,
                              ValueFromPipeline = $True,
                              ValueFromPipelineByPropertyName = $True,
                              HelpMessage = 'Enter flavor'
                             )
    
                   ]
                           
                   [ValidateSet("Chocolate", "Strawberry", "Vanilla")]
    
                   [String[]]$Flavor
    
             )
    
             BEGIN {}
    
             PROCESS {
    
                      Try { 
    
                           Write-Output "Flavor selected: $Flavor"
                      
                      }
                      
                      Catch [System.Management.Automation.ParameterBindingException] {
                      
                           $ErrorMessage = $_.Exception.Message
    
                           Write-Output "This failed" #"Error: [$ErrorMessage]" 
                      
                      }
             
             }
    
             END {}
    
    } # End Get-Example
    
    Get-Example -Flavor Mango
    

    How do I capture the error if the user types a "wrong" value? I've been researching but the solutions I found didn't work for me.

    Any guidance will be appreciated.

  • #146316

    Moderator
    Points: 1,972
    Helping Hand
    Rank: Community Hero

    The error won't be handled by the process block. Its verified and thrown during ParameterBinding process. Do a trace to get more insights.

    Trace-Command -Name ParameterBinding -Expression {Get-Example -Flavor Mango} -PSHost

You must be logged in to reply to this topic.

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort