就你的情況而言,只需用圓括號包圍表達式就可以將它傳遞給你的函數。
您需要這樣做,因爲PowerShell根據命令的開始具有多個解析模式。
表達模式類似於大多數其他語言解析 - 數字是數字和字符串被引用。
命令模式將所有內容視爲除變量和括號之外的字符串。這裏的字符串不需要被引用。
1+2 Expression mode - starts with number
"string" Expression mode - starts with quote
string Command mode - starts with letter
& "string" Command mode - starts with &
. "string" Command mode - starts with . and a space
.123 Expression mode - starts with . and number (without space)
.string Command mode - starts with a . that is part of a command name
通過用圓括號括起命令,可以在一行中混合模式。
你可以看到這個效果,如果你以下面的方式定義函數abs:
function Abs($value)
{
Write-Host $args
if($value -lt 0) { -$value } else { $value }
}
Abs 1 + 2
#Prints: + 2
#Returns: 1
Abs 1+2
#Prints:
#Returns: 1+2
Abs (1 + 2)
#Prints:
#Returns: 3
Abs (1+2)
#Prints:
#Returns: 3
謝謝你解釋模式。我不知道它甚至有不同的模式,因爲我迄今發現的教程都沒有提到任何這樣的事情。我沒有嘗試parens,因爲我之前遇到過一個問題,那就是用parens調用一個函數,在那裏它傳遞了所有參數的單個數組(作爲第一個參數),而不是參數在適當的位置。 – rmeador 2010-05-21 22:09:20
@rmeador強烈推薦使用PowerShell :)這些模式也在那裏解釋。這是第1本書。 – stej 2010-05-22 12:10:49