Strange StringBuilder

I have a StringBuilder object inside a function. Before returning the string type , then 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()

Conclusion:

FIRST OUT:  aaa
bbb
ccc
 OUTTYPE: System.String -> THAT OK
-------------------
SECOND OUT2 (ALL ARE four times - WHY???):  aaa
bbb
ccc
 aaa
bbb
ccc
 aaa
bbb
ccc 
 aaa
bbb
ccc
 OUT2TYPE: System.Object[] -> Object?????

Why all four times? Why is the object not a string?

+4
source share
1 answer

Just try the following:

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()

The explanation is that it $stringBuilder.AppendLine()outputs something and is added to the output of the function.


: , . , PowerShell - return keywork ($ out), , ( ). about_Return, ,

Windows PowerShell     , , Return.

+5

All Articles