The Wiert Corner – irregular stream of stuff

Jeroen W. Pluimers on .NET, C#, Delphi, databases, and personal interests

  • My badges

  • Twitter Updates

  • My Flickr Stream

  • Pages

  • All categories

  • Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 1,680 other followers

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

Posted by jpluimers on 2019/08/13

[WayBackIn Powershell, what kind of data type is [string[]] and when would you use it? (thanks cignul9 and arco444!): basically it forces an array of string.

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.

–jeroen

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

 
%d bloggers like this: