PowerShell And StringBuilder

Alex Yeung picture Alex Yeung · Oct 18, 2011 · Viewed 30k times · Source

I am new in PowerShell but am familiar with .NET classes.

I am using System.Text.StringBuilder in PowerShell script. The script is that

Function MyStringFunc([String]$line) {
    $r = New-Object -TypeName "System.Collections.Generic.List``1[[System.String]]";
    $sb = New-Object -TypeName "System.Text.StringBuilder";

    foreach ($c in $line) {
        $sb.Append($c);
        $r.Add($sb.ToString());
    }

    return $r;
}

$line1 = "123";
$a = MyStringFunc $line1;
$a

I expected the result is

1
12
123

However the result is

                  Capacity                MaxCapacity                    Length
                  --------                -----------                    ------
                        16                 2147483647                         3
123

Did I do something wrong?

Answer

Keith Hill picture Keith Hill · Oct 18, 2011

Several of the methods on StringBuilder like Append IIRC, return the StringBuilder so you can call more StringBuilder methods. However the way PowerShell works is that it outputs all results (return values in the case of .NET method calls). In this case, cast the result to [void] to ignore the return value e.g.:

[void]$sb.Append($c)

Note that you don't need to end lines in ; in PowerShell. However if you put multiple commands on the same line then use ;' to separate those commands.