powershellvalidateset

Powershell - Why does [ValidateSet("varA", "varB")] not set $LASTEXITCODE?


I wondered that scripts whose parameter are validated by the ValidateSet attribute do not return any invalid $LASTEXITCODE when invalid parameters are given.

Let's say I have the following PowerShell script, called try.ps1:

#INPUT Variables for the Script
Param(
    [Parameter(Mandatory)]
    [ValidateSet("a", "b")]
    [string] $first_param,

    [Parameter(Mandatory)]
    [ValidateSet("c", "d")]
    [string] $second_param
)

exit 0

If I call it now in PS via PS C:\Users\MyUser> .\try.ps1 -first_param n -second_param c (invalid $first_param) I get a ParameterBindingValidationException with an Error called ParameterArgumentValidationError but this seems not not set my $LASTEXITCODE variable, but why not?

So how is it possible for me (without bloating my code and validating each of my variables in some if-else statements to trigger an error) to get $LASTEXITCODE=1 back when calling my script with invalid params?


Solution

  • tl;dr

    See also:

    Read on for some additional conceptual information.


    Background information:

    Unfortunately, the excerpt from the documentation in Josef Z's answer is only partly correct (in short: $LASTEXITODE is set in response to exit $number calls in scripts in-session, and $number is reported as the specific exit code in -File CLI calls - GitHub docs issue #10046 aims to get the documentation corrected).
    Let me present what I believe to be the correct (bigger) picture:


    [1] Curiously, exit quietly accepts and effectively ignores an argument that either isn't numeric or cannot be coerced to a number, so a call such as exit (Get-Date) is effectively the same as exit and therefore sets $LASTEXITCODE / the exit code to 0