Working with Arrays

by Nov 19, 2008

Creating arrays in PowerShell is easy using the comma delimiter. The next line creates an array with five elements:

$myArray = 'Hello', 12, (Get-Date), $null, $true
$myArray.Count

To access array elements, use square brackets and the element index number. The index always starts at 0. To get the first element, type this:

$myArray[0]

Negative index numbers count backwards so to get the last element, use -1:

$myArray[-1]

You can also use arrays as index and select more than one element. The next line retrieves the first, the second and the last element:

$myArray[0,1,-1]

To discard the last two elements, select the remaining elements and reassign them:

$myArray = $myArray[0..2]
$myArray.Count

To add a new element to an existing array, simply use +=:

$myArray += 'new element'
$myArray.Count

Finally, to create a strongly typed array, you should add the type in front of your array definition and append the type with an opening and a closing square bracket. The following array only accepts integer values:

[int[]]$myArray = 1,2,3
$myArray += 12
$myArray += 14.678
$myArray[-1]
$myArray += 'this won't work because it is not convertible to integer'