Arrays with a type

An array may be given a type in similar manner to a variable holding a single value. The difference is that the type name is followed by [], as was the case when creating an empty array of a specific size. For example, each of these is an array type, which may appear before a variable name:

[String[]]      # An array of strings 
[UInt64[]]      # An array of unsigned 64-bit integers 
[Xml[]]         # An array of XML documents 

If a type is set for the array, more care must be taken as regards assigning values. If a type is declared, PowerShell will attempt to convert any value assigned to an array element into that type.

In this example, $null will become 0 and 3.45 (a double) will become 3 (normal rounding rules apply when converting integers):

[Int32[]]$myNumbers = 1, 2, $null, 3.45 

The following example shows an error being thrown, as a string cannot be converted into an integer:

PS> [Int32[]]$myNumbers = 1, 2, $null, "A string"
Cannot convert value "A string" to type "System.Int32". Error: "Input string was not in a correct format."
At line:1 char:1
+ [Int32[]]$myNumbers = 1, 2, $null, "A string"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : MetadataError: (:) [], ArgumentTransformationMetadataException
+ FullyQualifiedErrorId : RuntimeException
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.152.251