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

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:


Negative index numbers count backwards so to get the last element, use -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:


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

$myArray = $myArray[0..2]

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

$myArray += 'new element'

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 += 'this won't work because it is not convertible to integer'