我发现,与普通脚本相比,格式运算符在函数内的工作方式不同。 这是一个简单的例子,说明了什么是按预期工作的:
[string]$name = 'Scripting Guy'
[string]$statement = 'PowerShell rocks'
$s = "The {0} thinks that {1}!" -f $name, $statement
write-host $s
制造
The Scripting Guy thinks that PowerShell rocks!
虽然在函数内部它做了不同的事情:
function myFunc( [string] $iname, [string] $istatement) {
$s = "The {0} thinks that {1}!" -f $iname, $istatement
write-host $s
}
[string]$name = 'Scripting Guy'
[string]$statement = 'PowerShell rocks'
myFunc($name, $statement)
产生
The Scripting Guy PowerShell rocks thinks that !
我试着用它来发现它在做什么:
function myFunc( [string] $iname, [string] $istatement) {
$s = "The {0} thinks that {1}! {2} {3}" -f $iname, $istatement, "=====", $iname
write-host $s
}
[string]$name = 'Scripting Guy'
[string]$statement = 'PowerShell rocks'
myFunc($name, $statement)
这会产生:
The Scripting Guy PowerShell rocks thinks that ! ===== Scripting Guy PowerShell rocks
所以现在我不知道该怎么想。
答案 0 :(得分:3)
您应该按如下方式调用该函数:
myFunc -iname "Scripting Guy" -istatement "Powershell Rocks!!"
或
myFunc $name $statement
您正在使用的当前方法传递单个数组对象,这就是元素连续打印的原因