I'm trying to find info about when you would use [string[]]$MyStuff
. Is this an array of characters, or just an array with elements that are explicitly strings, or ...?
I've seen this used in script samples and it's really not clear. Often I've seen it used for variables that receive output of some non-native utility's text, or as the data type for an input parameter of a function.
What do those extra brackets mean?
It defines an array of strings. Consider the following ways of initialising an array:
[PS] > [string[]]$s1 = "foo","bar","one","two",3,4
[PS] > $s2 = "foo","bar","one","two",3,4
[PS] > $s1.gettype()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String[] System.Array
[PS] > $s2.gettype()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
By default, a powershell array is an array of objects that it will cast to a particular type if necessary. Look at how it's decided what types the 5th element of each of these are:
[PS] > $s1[4].gettype()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String System.Object
[PS] > $s2[4].gettype()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Int32 System.ValueType
[PS] > $s1[4]
3
[PS] > $s2[4]
3
The use of [string[]]
when creating $s1
has meant that a raw 3
passed to the array has been converted to a String
type in contrast to an Int32
when stored in an Object
array.
It is a string array. For example:
[string[]] $var = @("Batman", "Robin", "The Joker")
So then you can access your array like so:
$var[0]
Returns "Batman"
$var[1]
Returns "Robin". And so on.
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