【问题标题】:ValidateScript Parameter validationValidateScript 参数验证
【发布时间】:2017-04-25 11:36:02
【问题描述】:

这一行:

[ValidateScript({if (!(Test-Path $_) -and (!($_ -like "*.exe"))) 
{ Throw "Specify correct path to executable." }
else {$true}})]
[String]$installerPath

Test-Path 验证返回 True/False。

但是 ! -like 没有按预期工作。使用 .txt、.msi 等文件类型传递参数无法正确验证。

【问题讨论】:

    标签: powershell


    【解决方案1】:

    为了更清晰的验证,我会拆分检查并提供不同的错误消息:

    [ValidateScript({
        if(-Not Test-Path $_ ){ throw "$_ does not exist." }
        if(-Not ($_ -like "*.exe")){ throw "Input file must be an executable." }
        $true
    })]
    [String]
    $installerPath
    

    不需要“else”,因为抛出会立即退出。

    【讨论】:

      【解决方案2】:

      我会简单地交换 if-else 块并删除 否定 (!):

      [ValidateScript(
      {
          if ((Test-Path $_) -and ($_ -like "*.exe")) 
          { 
              $true
      
          }
          else 
          {
              Throw "Specify correct path to executable." 
          }
      })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-09-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-01
        • 2017-06-27
        • 2015-02-04
        相关资源
        最近更新 更多