Arguments may be passed to the class constructor using a number of different approaches.
Using New-Object and the ArgumentList parameter, passing a single argument will use the second constructor in the list on MSDN (and in PowerShell):
PS> New-Object -TypeName System.Text.StringBuilder -ArgumentList 10
Capacity MaxCapacity Length
-------- ----------- ------
10 2147483647 0
Alternatively, the following two approaches may be used:
New-Object System.Text.StringBuilder(10) [System.Text.StringBuilder]::new(10)
PowerShell decides which constructor to use based on the numbers and types of the arguments.
In the previous examples, one argument is passed; there are two possible constructors that accept a single argument. One of these expects a value of the Int32 type, the other a string.
If a string is passed, StringBuilder will be created, with an initial value for the string. The following example creates a StringBuilder object instance containing the specified ('Hello world') string:
PS> $stringBuilder = New-Object System.Text.StringBuilder('Hello world')
PS> $stringBuilder.ToString()
Hello world
PowerShell will attempt to find a constructor, even if the value type used does not exactly match one of the definitions. For example, an argument of $true, a Boolean, creates a StringBuilder object with a capacity set to 1. The value for $true is treated as an Int32 value by PowerShell:
PS> New-Object System.Text.StringBuilder($true)
Capacity MaxCapacity Length
-------- ----------- ------
1 2147483647 0
If the value for the argument does not match any of the possible constructors, an error will be thrown:
PS> New-Object System.Text.StringBuilder((Get-Date))
New-Object : Cannot convert argument "0", with value: "23/01/2017 15:26:59", for "StringBuilder" to type "System.Int32": "Cannot convert value "23/01/2017 15:26:59" to type
"System.Int32". Error: "Invalid cast from 'DateTime' to 'Int32'.""
At line:1 char:1
+ New-Object System.Text.StringBuilder((Get-Date))
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [New-Object], MethodException
+ FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand