PowerShell cmdlet parameter validation

纵饮孤独 提交于 2019-12-20 01:09:13

问题


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:


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



来源:https://stackoverflow.com/questions/1538230/powershell-cmdlet-parameter-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!