11.1. Arrays

An array is a collection of data elements. In Windows PowerShell, an array can contain elements of any type supported by the .NET Framework. Array elements in the Windows PowerShell language are numbered from zero. The first element in the array is element 0, the second is element 1, and so on.

To create an array, assign multiple values to a variable. To create a simple array named $myArray containing three elements, type the following command:

$myArray = 1, 2, 3

You can display all elements in the array simply by typing


at the Windows PowerShell prompt. If you want to display a selected element of the array, supply the number of the element in square brackets. For example, to display the first element of the $myArray variable, just type:


Figure 11-1 shows the execution of the preceding commands.

Figure 11.1. Figure 11-1

The names of arrays are case-insensitive, so typing:




or any other variant of case will all display the values of the same array.

As I mentioned earlier, in Windows PowerShell, an array can contain various .NET types in individual elements of an array. To create an array with three .NET types, type the following at the command prompt:

$mixedArray = 1, "Hello", 2.55

To display the elements in the array, type:


You can find the methods available on $mixedArray and on each of its elements by using ...

Get Professional Windows® PowerShell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.