2016-09-21 87 views
0

如果我调用该函数没有默认值工作功能命名参数问题默认

当我打电话与名为参数的函数,我离开他们的一个空白,我得到一个错误的任何参数...任何方式来纠正这个?

下面是函数

function foo { 
    Param(
    [string]$a, 
    [string]$b = "bar", 
    [bool]$c = $false 
) 

    Write-Host "a:", $a, "; b:", $b, "; c:", $c 
} 
foo "hello" 

回报a: hello ; b: bar ; c: False

foo -a test -b test -c $true 

返回a: test ; b: test ; c: True

foo -a test -b test -c 

抛出一个错误:当你省略该参数完全

foo : Missing an argument for parameter 'c'. Specify a parameter of type 'System.Boolean' and try again.

回答

1

一个参数的默认值分配。如果提供参数但省略值$null已通过。

代替使用布尔参数通常最好使用开关:

function foo { 
    Param(
    [string]$a, 
    [string]$b = "bar", 
    [Switch][bool]$c 
) 

    Write-Host "a: $a`nb: $b`nc: $c" 
} 

一个开关的值被自动$false省略时和$true当存在时。

PS C:\>foo -a test -b test -c:$true 
a: test 
b: test 
c: True 
PS C:\>foo -a test -b test -c:$false 
a: test 
b: test 
c: False
0

您正在使用[BOOL]为$ C类型:

PS C:\>foo -a test -b test -c 
a: test 
b: test 
c: True 
PS C:\>foo -a test -b test 
a: test 
b: test 
c: False

你也可以明确地传递这样的值。

foo -a test -b test -c 

那是因为你是在告诉PowerShell的:如果你是这样做的PowerShell通过调用预期值不要使用默认的声明,我要覆盖默认,但你不能告诉哪个值的PowerShell应该使用而不是默认值。

我认为你正在寻找的是你的功能[开关]。 尝试:

function foo { 
    param([string] $a, [string]$b = "bar", [switch] $c) 

    Write-Host "a:", $a, "; b:", $b, "; c:", $c 
} 

foo "hello" -c 

结果将是:

a: hello ; b: bar ; c: True 

如果不使用-c开关$ C将是$假的。

更多信息可以在这里找到:https://msdn.microsoft.com/en-us/library/dd878252(v=vs.85).aspx - >开关参数