我在函数内部有StringBuilder对象。返回前有 string-type ,之后有 System.Object 。
function test
{
$strArr = @("aaa", "bbb", "ccc")
$stringBuilder = New-Object System.Text.StringBuilder
foreach ($item in $strArr)
{
$stringBuilder.AppendLine($item)
}
$out = $stringBuilder.ToString()
write-host "FIRST OUT: ", $out, "OUTTYPE:", $out.GetType()
return $out
}
$out2 = test
Write-Host "-------------------"
write-host "SECOND OUT2: ", $out2, "OUT2TYPE:", $out2.GetType()
输出:
FIRST OUT: aaa
bbb
ccc
OUTTYPE: System.String -> THAT'S OK
-------------------
SECOND OUT2 (ALL ARE four times - WHY???): aaa
bbb
ccc
aaa
bbb
ccc
aaa
bbb
ccc
aaa
bbb
ccc
OUT2TYPE: System.Object[] -> Object?????
为什么这四次都是?为什么对象不是字符串?
答案 0 :(得分:5)
试试这个:
function test
{
$strArr = @("aaa", "bbb", "ccc")
$stringBuilder = New-Object System.Text.StringBuilder
foreach ($item in $strArr)
{
$stringBuilder.AppendLine($item) | Out-Null
}
$out = $stringBuilder.ToString()
write-host "FIRST OUT: ", $out, "OUTTYPE:", $out.GetType()
return $out
}
$out2 = test
Write-Host "-------------------"
write-host "SECOND OUT2: ", $out2, "OUT2TYPE:", $out2.GetType()
解释是$stringBuilder.AppendLine()
输出了一些内容,并将其添加到函数的输出中。
编辑:
函数输出的所有内容都被视为函数的返回。换句话说,在PowerShell中,函数的返回值不仅是return
keywork($ out)之后的值,而且是函数内部的所有数据(以数组形式)。看about_Return我们看到了
在Windows PowerShell中,每个语句的结果都返回为 输出,即使没有包含Return关键字的语句。