2016-09-21 85 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 - >開關參數