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

2 months, 3 weeks ago.

  • Author
  • #146310

    Topics: 9
    Replies: 45
    Points: 17
    Rank: Member

    I have the following example:

    $ErrorActionPreference = 'Stop'
    Function Get-Example {
                   [Parameter(Mandatory = $True,
                              ValueFromPipeline = $True,
                              ValueFromPipelineByPropertyName = $True,
                              HelpMessage = 'Enter flavor'
                   [ValidateSet("Chocolate", "Strawberry", "Vanilla")]
             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

    Topics: 8
    Replies: 878
    Points: 2,690
    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.