PowerShell arrays

An array is a collection of objects. PowerShell arrays can be created manually

PS> $a = 1,2,3,4

or

$b = @(1,2,3,4)

PowerShell will also create arrays automatically when needed:

PS> $ps = Get-Process

All three options are arrays:

PS> $a.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array

PS> $b.GetType()
IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array

PS> $ps.GetType()
IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array

The individual elements in an array are accessed using an index that starts at 0

PS> $a[0]
1

You can use a range of indices

PS> $a[1..2]
2
3

You can use negative indices to count from the end of the array

PS> $a[-1]
4

PS> $a[-1..-2]
4
3

PowerShell arrays are polymorphic by default meaning you can store any type of object in an array – and can store multiple types of objects in a single array

PS> $a += ‘Hello World’

PS> $a
1
2
3
4
Hello World

We haven’t actually extended the array –  a new array is created that contains the old array and the new element. Any time you find yourself adding elements to an array in a loop – STOP and think about how you could do this as a pipeline.

PS> $x = @()

PS> 1..5 | foreach {$x += $_}

PS> $x -join ‘ ‘
1 2 3 4 5

is very inefficient compared to

PS> $y = 1..5 | foreach {$_}

PS> $y -join ‘ ‘
1 2 3 4 5

As you saw earlier you can add elements to an existing array. You can also remove elements from an array:

PS> $a = $a -ne 3

PS> $a
1
2
4
Hello World

Iterating over the contents of an array is as simple as

PS> $a | foreach {$_}

or

PS> foreach ($i in $a){$i}

PowerShell arrays are powerful tools that can make your coding much easier. This post has covered the most likely tasks you’ll face using arrays in PowerShell

Advertisements
This entry was posted in Powershell. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s