就你的情况而言,只需用圆括号包围表达式就可以将它传递给你的函数。
您需要这样做,因为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