Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

powershell

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?

like image 697
Cignul9 Avatar asked Nov 05 '14 15:11

Cignul9


2 Answers

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.

like image 152
arco444 Avatar answered Nov 14 '22 09:11

arco444


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.

like image 24
Samuel Prout Avatar answered Nov 14 '22 09:11

Samuel Prout