【发布时间】:2009-04-07 22:57:13
【问题描述】:
考虑这样的功能:
function Test($foo, $bar)
{
...
}
我们可以这样称呼它:
Test -foo $null
Test
我如何知道 -foo 何时被省略,何时为 $null?
【问题讨论】:
标签: function powershell arguments
考虑这样的功能:
function Test($foo, $bar)
{
...
}
我们可以这样称呼它:
Test -foo $null
Test
我如何知道 -foo 何时被省略,何时为 $null?
【问题讨论】:
标签: function powershell arguments
如果您使用的是 Powershell V2 或更高版本,则可以使用 $PSBoundParameters 变量,它是一个字典,列出了当前范围内的所有绑定参数。
请参阅讨论它的 this 博客文章。
【讨论】:
除非可以捕获从 param 语句抛出的异常(并且由于 param 必须是第一个,我看不出这会起作用):
function {
trap { "Something failed" }
param($foo = $(throw "Foo not specified"))
...
然后我看不到方法(使用 [switch] 参数得到相同的结果:默认或显式 -mySwitch:$false)。
【讨论】:
基于理查德想法的解决方案:
$missed = "{716C1AD7-0DA6-45e6-854E-4B466508EB96}"
function Test($foo = $missed, $bar)
{
if($foo -eq $missed) {
Write-Host 'Missed'
}
else
{
Write-Host "Foo: $foo"
}
}
Test -foo $null
Test
【讨论】: