Skip to content

Improve UX for use of validation attributes in scripts #26772

@MartinGC94

Description

@MartinGC94

Summary of the new feature / enhancement

If you set up a function like this:

function Demo
{
    Param
    (
        [Parameter()]
        [ValidateNotNull()]
        [ValidateScript({$_ -is [int]})]
        [ValidateRange(1, 10)]
        $VMCount
    )
    $VMCount
}

And you try to run it with a value that fails any of the validation steps the error message you get will tell you precisely what went wrong. For example if you provide a null value you'll get:

Demo: Cannot validate argument on parameter 'VMCount'. The argument is null, empty, or an element of the argument collection contains a null value. Supply a collection that does not contain any null values and then try the command again.

and if you provide a value greater than 10 you get this:

Demo: Cannot validate argument on parameter 'VMCount'. The 11 argument is greater than the maximum allowed range of 10. Supply an argument that is less than or equal to 10 and then try the command again.

If you try to do the same validation inside a script however, then you just get a generic error message:

PS C:\> [ValidateNotNull()]
        [ValidateScript({$_ -is [int]})]
        [ValidateRange(1, 10)]
        $VMCount = 11
MetadataError: The attribute cannot be added because variable VMCount with value 11 would no longer be valid.
PS C:\>

It would be better if the error message was the same as the parameter message, except with the word "parameter" replaced with the word "Variable".
Another problem is that if you try and catch this error you can't really get the variable name or the failed attribute because the Error record/Exception details don't have this data in any of the available properties, so you can't even re-throw it yourself if needed.

Proposed technical implementation details (optional)

``

Metadata

Metadata

Assignees

No one assigned

    Labels

    Issue-Enhancementthe issue is more of a feature request than a bugNeeds-TriageThe issue is new and needs to be triaged by a work group.WG-Enginecore PowerShell engine, interpreter, and runtimeWG-NeedsReviewNeeds a review by the labeled Working Group

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions