Wednesday, 11 September 2013

How to validate dependent parameters in PowerShell cmdlet

How to validate dependent parameters in PowerShell cmdlet

What's the best way to do PowerShell cmdlet validation on dependent
parameters? For example, in the sample cmdlet below I need to run
validation that Low is greater than High but that doesn't seem to be
possible with validation attributes.
[Cmdlet(VerbsCommon.Get, "FakeData")]
public class GetFakeData : PSCmdlet
{
[Parameter(Mandatory = true)]
[ValidateNotNullOrEmpty]
public int Low { get; set; }
[Parameter(Mandatory = true)]
[ValidateNotNullOrEmpty]
public int High { get; set; }
protected override void BeginProcessing()
{
if (Low >= High)
{
// Is there a better exception to throw here?
throw new CmdletInvocationException("Low must be less than
High");
}
base.BeginProcessing();
}
protected override void OnProcessRecord()
{
// Do stuff...
}
}
Is there is a better way to do this? The main thing I don't like about the
solution above is that I can't throw a ParameterBindingException like the
validation attributes would do since it's an internal class. I could throw
ArgumentException or PSArgumentException but those are really for Methods
not cmdlets.

No comments:

Post a Comment