Powershell Arrays - PowerShell - SS64.com (2024)

  • SS64
  • PowerShell
  • How-to

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:

01234
64Hello3.5WorldDemo

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.

012
0catsdogsravens
1405060

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

Powershell Arrays - PowerShell - SS64.com (2024)
Top Articles
Yes, You Can Donate Old TV Sets
Is Coding Hard to Learn? What Developers Say - Multiverse
English Bulldog Puppies For Sale Under 1000 In Florida
Katie Pavlich Bikini Photos
Gamevault Agent
Pieology Nutrition Calculator Mobile
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Compare the Samsung Galaxy S24 - 256GB - Cobalt Violet vs Apple iPhone 16 Pro - 128GB - Desert Titanium | AT&T
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Craigslist Dog Kennels For Sale
Things To Do In Atlanta Tomorrow Night
Non Sequitur
Crossword Nexus Solver
How To Cut Eelgrass Grounded
Pac Man Deviantart
Alexander Funeral Home Gallatin Obituaries
Shasta County Most Wanted 2022
Energy Healing Conference Utah
Geometry Review Quiz 5 Answer Key
Hobby Stores Near Me Now
Icivics The Electoral Process Answer Key
Allybearloves
Bible Gateway passage: Revelation 3 - New Living Translation
Yisd Home Access Center
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
Marquette Gas Prices
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Vera Bradley Factory Outlet Sunbury Products
Pixel Combat Unblocked
Movies - EPIC Theatres
Cvs Sport Physicals
Mercedes W204 Belt Diagram
Mia Malkova Bio, Net Worth, Age & More - Magzica
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Teenbeautyfitness
Where Can I Cash A Huntington National Bank Check
Topos De Bolos Engraçados
Sand Castle Parents Guide
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Holzer Athena Portal
Hello – Cornerstone Chapel
Stoughton Commuter Rail Schedule
Selly Medaline
Latest Posts
Article information

Author: Arielle Torp

Last Updated:

Views: 5814

Rating: 4 / 5 (41 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Arielle Torp

Birthday: 1997-09-20

Address: 87313 Erdman Vista, North Dustinborough, WA 37563

Phone: +97216742823598

Job: Central Technology Officer

Hobby: Taekwondo, Macrame, Foreign language learning, Kite flying, Cooking, Skiing, Computer programming

Introduction: My name is Arielle Torp, I am a comfortable, kind, zealous, lovely, jolly, colorful, adventurous person who loves writing and wants to share my knowledge and understanding with you.