0

我希望在 -h 不传递值的情况下像 -h 使用参数一样工作:但是,我希望其他人保持原样......也就是说,它们是可选的,除非您为参数设置别名并且您需要提供价值。

Param(
$BadParam,
[alias("h")][String]$Help,
[alias("s")][String]$Server,    
[alias("d")][String]$DocRoot,
[alias("c")][String]$Commit,
[alias("b")][String]$Branch
)

例如(因为缺乏更好的):

if(!$Help)
{
Write-Host "Here's the menu for how it works bro."
}

if($Help)
{
Write-Host "Here's more info on that particular thing from the menu."
}

我希望这在 shell 中表现如何:

-> script.ps1 -s test -h
-> Here's the menu for how it works bro.

-> script.ps1 -s test -h server
-> Here's more info on that particular thing from the menu.

-> script.ps1 -s -h server
-> You are missing a value for -e.
4

1 回答 1

3

Powershell 并不真正支持这样的东西。您可以有一个[switch]可以不指定值的参数,也可以有一个[string]必须完全不存在或提供值的参数。您不能有一个支持不存在、不指定值和指定值的参数。

一种替代方法是 make it a [string],但让用户通过$null,但这很糟糕。

另一个非常 hacky 的替代方法是对参数位置进行一些技巧。 -Help可能是 a [switch],那么-ThingHelp在它之后可能还有另一个参数是 a [string]。然后看起来像的调用-Help 'foo'不是设置$Help'foo'而是设置$Help开关,并且还分配$ThingHelp = 'foo'.

function ParamTest
{
  param(
     [Parameter(Position = 0)]
     [switch]$Help,

     [Parameter(Position = 1)]
     [string] $ThingHelp

  )

   "Help is [$help]"
   "ThingHelp is [$thingHelp]"
}

这支持以下内容:

PS> ParamTest               # $help = $false, $thingHelp = null
PS> ParamTest -Help         # $help = $true, $thingHelp = null
PS> ParamTest -Help 'foo'   # $help = $true, $thingHelp = 'foo'

一般来说,像这样的黑客攻击并不是一个好主意,因为它们往往既脆弱又令人困惑。您应该能够将脚本提供给普通的 powershell 用户,他们应该立即了解您的参数的含义和用法。如果您必须解释一堆其他数千个 cmdlet 都没有做的自定义内容,那么您可能是在浪费每个人的时间。

如果您实际上是在实施某种帮助/使用系统,请停止!Powershell 免费提供全面的帮助系统。您可以记录每个参数,提供示例代码等,无需任何额外内容。有关基于注释的帮助,请参阅文档。

于 2012-09-17T18:20:49.180 回答