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?
In PowerShell, string concatenation is primarily achieved by using the “+” operator. There are also other ways like enclosing the strings inside double quotes, using a join operator, or using the -f operator. $str1="My name is vignesh."
If you are using two or three string concatenations, use a string. StringBuilder will improve performance in cases where you make repeated modifications to a string or concatenate many strings together. In short, use StringBuilder only for a large number of concatenations.
The PowerShell string is simply an object with a System. String type. It is a datatype that denotes the sequence of characters, either as a literal constant or some kind of variable. A String can be defined in PowerShell by using the single or double-quotes. Both the strings are created of the same System.
C# StringBuilder is similar to Java StringBuilder. A String object is immutable, i.e. a String cannot be changed once created. Every time when you use any of the methods of the System. String class, then you create a new string object in memory.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With