【问题标题】:How to validate dependent parameters in PowerShell cmdlet如何验证 PowerShell cmdlet 中的相关参数
【发布时间】:2013-09-16 05:02:38
【问题描述】:

对相关参数进行 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。

【问题讨论】:

    标签: c# validation powershell cmdlets cmdlet


    【解决方案1】:

    您需要类似 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 自定义错误的更多信息

    【讨论】:

    猜你喜欢
    • 2010-12-05
    • 1970-01-01
    • 1970-01-01
    • 2021-11-28
    • 1970-01-01
    • 2020-10-12
    • 1970-01-01
    • 1970-01-01
    • 2019-02-24
    相关资源
    最近更新 更多