我試圖了解 -switch 引數的行為,尤其是在將它們傳遞給其他函式時。
我的基本問題是:我如何必須將 switch 引數的變數傳遞給具有 switch 引數的另一個函式,以便變數保持其值。目前,看起來我總是將“true”傳遞給底層函式,只是因為傳遞了引數。
為了說明我的問題,我撰寫了這個測驗腳本:
function testswitch{
param(
[switch]$foo
)
if ($foo -eq $true) {
"testswitch yes"
} else {
"testswitch no"
}
}
function testbool{
param(
[bool]$foo
)
if ($foo -eq $true) {
"testbool yes"
} else {
"testbool no"
}
}
function test{
param(
[switch]$foo
)
"received value:"
if ($foo -eq $true) {
"test yes"
} else {
"test no"
}
"passed calls:"
testswitch -foo $foo
testbool -foo $foo
"negated calls:"
testswitch -foo (!$foo)
testbool -foo (!$foo)
}
cls
test
"-----"
test -foo
"-----"
test -foo:$false
回傳此輸出:
received value:
test no
passed calls:
testswitch yes
testbool no
negated calls:
testswitch yes
testbool yes
-----
received value:
test yes
passed calls:
testswitch yes
testbool yes
negated calls:
testswitch yes
testbool no
-----
received value:
test no
passed calls:
testswitch yes
testbool no
negated calls:
testswitch yes
testbool yes
正如你所看到的,“testswitch”總是回傳“yes”——這不是我想要的。不幸的是,在谷歌上很難找到關于 switch 引數的體面資訊,因為還有一個條件陳述句,它根據我能想出的關鍵字獲得了很多點擊。
uj5u.com熱心網友回復:
針對 a的引數系結[switch]很棘手,因為僅存在-SwitchName引數(之后沒有顯式引數值)就足夠了 - PowerShell 看到testswitch -foo $foo并轉到“用戶指定-foo存在,然后他們給了我一些不相關的位置引數$foo”。
要覆寫此行為,您可以使用冒號將引數緊密系結到 switch 引數:
testswitch -foo:$foo
... 或者您可以splat引數,PowerShell 將正確計算出如何傳遞引數:
testswitch @PSBoundParameters
這兩種方法都是“安全的”,例如。將顯式引數與任何引數型別的作品緊密系結:不會改變任何行為(除了現在正確系結的開關引數)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/420897.html
標籤:
