How-to: Create and use PowerShell Arrays

A PowerShell array holds a list of data items.
The data elements of a PowerShell array need not be of the same type, unless the data type is declared (strongly typed).

Creating Arrays

To create an Array just separate the elements with commas.

Create an array named $myArray containing elements with a mix of data types:

$myArray = 64,"Hello",3.5,"World"

or use explicit array cast syntax:

$myArray = @(64,"Hello",3.5,"World")

Using the array cast syntax @(...) allows anything between the parentheses to be treated as an array, it could be a single element, the output from other commands/expressions, they will always be treated as an array.

To distribute the values back into individual variables:

$var1,$var2,$var3,$var4 = $myArray

Create an array containing several numeric (int) values:

$myArray = 1,2,3,4,5,6,7

or using the range operator (..):

$myArray = (1..7)

or strongly typed:

[int[]]$myArray = 12,64,8,64,12

If you want to AVOID creating an array, place quotes around the string expression, PowerShell will then ignore any commas which may happen to be within the string:

$notAnArray = "one, two, three"

Create an empty array:

$myArray = @()

Create an array with a single element:

$myArray = @("Hello World")

Create a Multi-dimensional array:

$myMultiArray = @(
             (1,2,3),
             (40,50,60)
)

Add values to an Array.

This is done using the += operator

Append an extra element with a value of 'India' to the $countries array:

$countries += 'India'

Adding items to a large array can be quite slow, a PowerShell array variable is immutable - meaning that in the background it creates a whole new array that includes the new value and then discards the old array.
A faster alternative to use a .Net ArrayList:

$countries = New-Object System.Collections.ArrayList
$countries.Add('India') > $null
$countries.Add('Montenegro') > $null

Retrieve items from an Array

To retrieve an element, specify its number, PowerShell automatically numbers the array elements starting at 0.

So for example, this array:

PS C:\> $myArray = 64,"Hello",3.5,"World", "Demo"

Will have the automatic index numbers:

0 1 2 3 4
64 Hello 3.5 World Demo

Think of the index number as being an offset from the staring element.

Return all the elements in an array:

PS C:\> $myArray

Return the first element in an array:

PS C:\> $myArray[0]
64

Return index #3 (which is the 4th element):

PS C:\> $myArray[3]
World

Return the 2nd and 4th index from the array:

PS C:\> $myArray[2,4]
3.5 Demo

Return the 4th through to the 9th index from the array:

PS C:\> $myArray[4..9]

Return the 10th down to the 5th index from the array:

PS C:\> $myArray[10..5]

Return the last element in an array:

PS C:\> $myArray[-1]

Return the first element from the first row in a multi-dimensional array:

PS C:\> $myMultiArray[0][0]

You can also combine named elements with a range, separating them with a +
so $myArray[1,2+4..9] will return the elements at indices 1 and 2 and then 4 through 9 inclusive.

Return the length of an array (how many items are in the array):

$myArray.length

Loop through the elements in an array:

foreach ($element in $myArray) {$element}

Loop through the elements in an array using the pipeline:

$myArray | ForEach-Object {"This element is: [$PSItem]"}

In PowerShell 4.0+ arrays have the methods .Where() and .Foreach() a faster alternative to a traditional pipeline at the expense of a higher memory consumption:

@(Get-Service).Where({$_.Status -eq 'stopped'})

or omitting the parentheses:

@(Get-Service).Where{$_.Status -eq 'stopped'}

Comparisons -eq - gt -lt etc

With an array, comparison operators will work as a filter returning all the values which match.

PS C:\> $a = 1,2,3,2
PS C:\> $a -eq 2
2
2

Care must be taken with comparing NULLs, because this is a filter you must place the $null on the left side of the comparison.

PS C:\> $a -eq $null # fails: returns $null
PS C:\> $null -eq $a # works: returns $false

Multi-dimensional arrays

Create a Multi-dimensional array:

PS C:\> $MultiArray = @(
             ("cats","dogs","ravens"),
             (40,50,60)
        )

PowerShell will automatically number the array elements on an X-Y grid starting at 0.

  0 1 2
0 cats dogs ravens
1 40 50 60

PS C:\> $MultiArray[0][2]
ravens

These are actualy 'Jagged' arrays because the dimensions of each row can be a different size. This is very cost-effective storage.

Data Types

When you create an array without specifying a datatype, PowerShell will create the array as an object array.
To determine the data type of an array:

$myArray.gettype()

To create a strongly typed array, that can only contain values of one particular type, cast the variable as string[], long[], bool[], int32[] or any other valid data type.
To cast an array, place the array type enclosed in square brackets before the variable name.
e.g.

[int32[]]$stronglytyped = @(64,12,24,5000)

[int32[][]]$multi = @(
(64, 12, 24),
(65, 14, 48)
)

PowerShell is not case-sensitive so $myArray is treated the same as $Myarray

If you pipe an array to Get-Member, it will display information about the objects in the array. If you use Get-Member -InputObject, that will display information about the array itself:

get-member -inputobject $myArray

Edit Array values

To change values in an array after it has been created, use the assignment operator (=) to specify a new value.

$myArray[4] = 64

Alternatively use the SetValue method:

$myArray.SetValue(64,4)

$myMultiArray[2][4] = 128

Add one array to another.
This creates a new array containing all the values from the first two arrays:

$march = @(2, 3, 4, 5, 6)
$april = @(7, 8, 9, 10, 11, 12)
$all = $march + $april

Delete Elements from an Array

This has to be done by creating a new array based on the initial array minus the items that you don’t want:

# Create an array
$demo = @(2, 4, 6, 7)
# now copy all elements bar the last and store in a new array
$final = $demo | Where-Object { ($_ -ne 7) }

For large arrays it is much faster to step through the array with Foreach - example: removing empty elements

Delete an Array (by deleting the array variable)

Remove-Item variable:monthly_sales

“Nor shall you by your presence make afraid, The kingfisher, who looks down dreamily, At his own shadow gorgeously array'd” - Sir Edmund William Gosse

Related PowerShell Cmdlets

get-help about_array
Hash Tables - Store paired Keys and Values, also the SPLAT operator.
How-to: Variables and Operators - Create variable, add to value, subtract, divide.


 
Copyright © 1999-2024 SS64.com
Some rights reserved