views:

473

answers:

1

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?

+6  A: 

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).

Scott Saad
Exactly what I was looking for, thanks!
Paolo Tedesco