2013-10-03 44 views
3

具有以下功能:PowerShell的函数参数类型

function appendToSB([System.Text.StringBuilder]$sb, 
        [string]$value){ 
    [void]$sb.append($value) 
    $sb 
} 

$sb = new-object -typename system.text.stringbuilder 
$sb = appendToSb($sb, "1,") 

$sb.tostring() | out-host 

我想用使用StringBuilder的我该功能来构建字符串,但我收到以下错误:

appendToSB : Cannot process argument transformation on parameter 'sb'. Cannot convert the "System.Object[]" value of ty pe "System.Object[]" to type "System.Text.StringBuilder". At E:\powershell\test.ps1:8 char:11 + appendToSb([system.text.stringbuilder]$sb, "1,") + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidData: (:) [appendToSB], ParameterBindingArgumentTransformationException + FullyQualifiedErrorId : ParameterArgumentTransformationError,appendToSB

没有任何人可以解释函数/函数参数/返回值如何在PowerShell中工作?

回答

12

经典的PowerShell问题。调用命令或函数时,不要使用parens或逗号分隔的参数。例如:

appendToSb $sb "1," 

您只能在调用.NET方法时使用该语法。如果你使用Set-StrictMode -Version 2它会遇到这样的问题。你传递了什么($ sb,“1,”)是你将数组传递给单个参数的方式。从技术上来说,parens不是必需的,但不会改变数值,即你也可以像这样传递一个数组。$sb, ","