In Powershell, what kind of data type is [string[]] and when would you use it?

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.

Tags:

Powershell