如何在PowerShell cmdlet中验证相关参数

时间:2013-09-12 00:47:28

标签: c# validation powershell cmdlets cmdlet

对依赖参数执行PowerShell cmdlet验证的最佳方法是什么?例如,在下面的示例cmdlet中,我需要运行Low大于High的验证,但验证属性似乎不可能。

[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...
    }
}

有更好的方法吗?我不喜欢上面解决方案的主要问题是我不能像验证属性那样抛出ParameterBindingException,因为它是一个内部类。我可以抛出ArgumentExceptionPSArgumentException但这些实际上是针对方法而不是cmdlet。

1 个答案:

答案 0 :(得分:2)

您需要cmdlet get-random中的内容。 因为你不能在cmdlet中使用[validatescript()]属性,因为它只对运行时的powershell函数/脚本有效,你需要从microsoft.powershell.utility \ get-random中窃取这个想法:

值检查在BeginProcessing()中完成,并使用自定义错误ThrowMinGreaterThanOrEqualMax

protected override void BeginProcessing()
    {
      using (GetRandomCommand.tracer.TraceMethod())
      {
        if (this.SetSeed.HasValue)
          this.Generator = new Random(this.SetSeed.Value);
        if (this.EffectiveParameterSet == GetRandomCommand.MyParameterSet.RandomNumber)
        {
          if (this.IsInt(this.Maximum) && this.IsInt(this.Minimum))
          {
            int minValue = this.ConvertToInt(this.Minimum, 0);
            int maxValue = this.ConvertToInt(this.Maximum, int.MaxValue);
            if (minValue >= maxValue)
              this.ThrowMinGreaterThanOrEqualMax((object) minValue, (object) maxValue);
            this.WriteObject((object) this.Generator.Next(minValue, maxValue));
          }
          else
          {
            double min = this.ConvertToDouble(this.Minimum, 0.0);
            double max = this.ConvertToDouble(this.Maximum, double.MaxValue);
            if (min >= max)
              this.ThrowMinGreaterThanOrEqualMax((object) min, (object) max);
            this.WriteObject((object) this.GetRandomDouble(min, max));
          }
        }
        else
        {
          if (this.EffectiveParameterSet != GetRandomCommand.MyParameterSet.RandomListItem)
            return;
          this.chosenListItems = new List<object>();
          this.numberOfProcessedListItems = 0;
          if (this.Count != 0)
            return;
          this.Count = 1;
        }
      }
    }

...

private void ThrowMinGreaterThanOrEqualMax(object min, object max)
    {
      if (min == null)
        throw GetRandomCommand.tracer.NewArgumentNullException("min");
      if (max == null)
        throw GetRandomCommand.tracer.NewArgumentNullException("max");
      string errorId = "MinGreaterThanOrEqualMax";
      this.ThrowTerminatingError(new ErrorRecord((Exception) new ArgumentException(this.GetErrorDetails(errorId, min, max).Message), errorId, ErrorCategory.InvalidArgument, (object) null));
    }

您可以使用反编译器(dotPeak)查看其余代码,以了解有关cmdlet自定义错误的更多信息