2013-09-30 32 views
0

我發現格式運算符在函數內部與純腳本相比工作方式不同。 下面是按預期工作的一個簡單的例子:函數內的Powershell格式運算符

[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 

所以,現在我不知道該怎麼去想這個。

回答

3

你應該調用函數如下:

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

myFunc $name $statement 

您正在使用的電流方法傳遞一個數組對象,這就是爲什麼元素得到印刷連續