4

I'm writing a custom PowerShell cmdlet, and I would like to know which is the proper way to validate a parameter.
I thought that this could be done either in the property set accessor or during Cmdlet execution:

[Cmdlet(VerbsCommon.Add,"X")]
public class AddX : Cmdlet {

    private string _name;

    [Parameter(
        Mandatory=false,
        HelpMessage="The name of the X")]
    public string name {
        get {return _name;}
        set {
            // Should the parameter be validated in the set accessor?
            if (_name.Contains(" ")) { 
                // call ThrowTerminatingError
            }
            _name = value;
        }
    }

    protected override void ProcessRecord() {
        // or in the ProcessRecord method?
        if (_name.Contains(" ")) {
            // call ThrowTerminatingError
        }
    }
}

Which is the "standard" approach? Property setter, ProcessRecord or something completely different?

1 Answer 1

7

If possible, it's preferred that the parameters be validated by the runtime by specifying Validation Attributes on the parameter definition.

Windows PowerShell can validate the arguments passed to cmdlet parameters in several ways. Windows PowerShell can validate the length, the range, and the pattern of the characters of the argument. It can validate the number of arguments available (the count).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.