String 函数内部的Powershell格式运算符

String 函数内部的Powershell格式运算符,string,powershell,String,Powershell,我发现format操作符在函数中的工作方式与普通脚本不同。 下面是一个简单的示例,说明了什么工作正常: [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! 在函数内部

我发现format操作符在函数中的工作方式与普通脚本不同。 下面是一个简单的示例,说明了什么工作正常:

[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 !
The Scripting Guy PowerShell rocks thinks that ! ===== Scripting Guy PowerShell rocks
我试着玩它,看看它在做什么:

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

现在我不知道该怎么想。

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

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


当前使用的方法传递单个数组对象,这就是元素连续打印的原因。

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

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

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