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

I am trying to find information about when you will use [string[]]$MyStuff . Is it an array of characters or just an array with elements that are explicitly strings, or ...?

I saw that it was used in script samples, and it really is not clear. Often I saw how it was used for variables that receive the output of some text that is not inline, or as a data type for an input function parameter.

What do these extra brackets mean?

+6
source share
2 answers

It defines an array of strings. Consider the following ways to initialize 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, the powershell array is an array of objects that will be passed to a particular type if necessary. See how he determined what types the 5th element of each will be:

 [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 

Using [string[]] when creating $s1 meant that raw 3 passed to the array was converted to a String type, unlike Int32 if it was stored in an Object array.

+12
source

This is a string array. For instance:

 [string[]] $var = @("Batman", "Robin", "The Joker") 

So you can access your array as follows:

 $var[0] 

Returns Batman

 $var[1] 

Returns Robin. And so on.

+1
source

Source: https://habr.com/ru/post/977773/


All Articles