【问题标题】:Parameter validation参数验证
【发布时间】:2021-05-25 16:39:32
【问题描述】:

我试图验证一个名为“Collect”的参数只接受 3 个参数(基本、中等和完整),但是当我为“collect”参数分配一个“有效”值时,它得到一个“假”返回。

我就是这么做的:

[CmdLetBinding()]
param([string]$Collect)
)

if ($collect -ne ('basic' -or 'medium' -or 'full')) {
  Write-Host "'collect' is mandatory with mandatory values. For reference, use -help argument" -ForegroundColor Red
  exit
}

运行测试:

c:\script.ps1 -collect basic

'collect' is mandatory with mandatory values. For reference, use -help argument

PD: -我知道我可以使用 validateset,但这对我不起作用。 -我认为问题出在嵌套的 $collect -ne ('basic' -or 'medium' -or 'full'),但我该如何解决呢?

【问题讨论】:

  • [1] 你不能像这样链接逻辑运算符。 >>> ($collect -ne ('basic' -or 'medium' -or 'full')) grin] ///// [2] PoSh 有验证方法 - 看看下面... 使用参数验证简化您的 PowerShell 脚本 |脚本博客 — devblogs.microsoft.com/scripting/…
  • 为什么不直接使用ValidateSet 属性? [ValidateSet('basic','medium','full')]
  • “我知道我可以使用 validateset,但这对我不起作用。”

标签: powershell validateset


【解决方案1】:

-or 操作 总是 计算结果为 [bool] - 所以您的 if 条件基本上是 $collect -ne $true

您需要使用-notin 而不是-ne

if($collect -notin 'basic','medium','full'){ 
   # ...
}

或者更好的是,只需使用ValidateSet 属性:

param(
  [ValidateSet('basic','medium','full')]
  [string]$Collect
)

【讨论】:

  • Validateset 的问题是,如果我建立了一个 -help 参数(例如:[switch]$help; if ($help){write-host "help output"}) -help 不起作用单独没有 -collect 太
  • @Richard 解决方案是不要尝试通过定义自己的自定义 -help 参数来重新发明轮子 :-)
  • 我刚开始学习powershell。那么你的意思是我可以使用一个默认的“-help”参数吗?有什么例子或参考吗?
  • @Richard 是的。这是-?,而不是-help。喜欢,.\path\to\yourScript.ps1 -?
猜你喜欢
  • 1970-01-01
  • 2018-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-01
  • 2017-06-27
  • 2015-02-04
相关资源
最近更新 更多