0

我发现格式运算符在函数内部的工作方式与普通脚本不同。这是一个按预期工作的简单示例:

[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

所以现在我不知道该怎么想。

4

1 回答 1

3

您应该按如下方式调用该函数:

myFunc -iname "Scripting Guy" -istatement "Powershell Rocks!!"

或者

myFunc $name $statement

您正在使用的当前方法传递一个数组对象,这就是元素被连续打印的原因

于 2013-09-30T15:33:01.087 回答