c# - 如何验证 PowerShell cmdlet 中的相关参数

标签 c# validation powershell powershell-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。

最佳答案

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

值检查在 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 自定义错误的更多信息

关于c# - 如何验证 PowerShell cmdlet 中的相关参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18753598/

相关文章:

c# - 删除文本文件中的空行

C# 跨线程操作调用后无效

c# - 单击按钮时如何检查已经打开的窗口?

java - 发生 jsf 验证错误时执行操作

powershell - 对 Powershell 作用域处理 v2/v3 的未记录更改?

c# - 使用本地 Visual Studio 负载测试在 ASP.NET MVC 和 IIS 中进行异步/等待的概念验证

javascript - knockout 日期验证无法正常工作

java - 在 Struts2 中结合 Validate Method 和 xml 验证

arrays - 如何在Powershell中创建数组的空数组?

powershell - 找不到计算机的唯一ID AD属性