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
Titan: Members-Only Wealth Platform
Earned Income Credit Eligibility for Foreign Earners
Walgreens Harry Edgemoor
Cranes For Sale in United States| IronPlanet
Hotels Near 625 Smith Avenue Nashville Tn 37203
Roblox Roguelike
Skyward Houston County
Stretchmark Camouflage Highland Park
Goodbye Horses: The Many Lives of Q Lazzarus
Bluegabe Girlfriend
Globe Position Fault Litter Robot
Missing 2023 Showtimes Near Landmark Cinemas Peoria
Craigslist Blackshear Ga
Bfg Straap Dead Photo Graphic
Tnt Forum Activeboard
Star Wars: Héros de la Galaxie - le guide des meilleurs personnages en 2024 - Le Blog Allo Paradise
Delaware Skip The Games
Stoney's Pizza & Gaming Parlor Danville Menu
Evil Dead Rise Showtimes Near Pelican Cinemas
Hannaford To-Go: Grocery Curbside Pickup
Hampton University Ministers Conference Registration
Turbo Tenant Renter Login
Helpers Needed At Once Bug Fables
Jailfunds Send Message
Isablove
Perry Inhofe Mansion
6465319333
Craigslist Central Il
Flixtor Nu Not Working
Rust Belt Revival Auctions
Ark Unlock All Skins Command
Rocketpult Infinite Fuel
The Best Carry-On Suitcases 2024, Tested and Reviewed by Travel Editors | SmarterTravel
Clark County Ky Busted Newspaper
Bimar Produkte Test & Vergleich 09/2024 » GUT bis SEHR GUT
That1Iggirl Mega
Telugu Moviez Wap Org
140000 Kilometers To Miles
Andrew Lee Torres
Ferguson Showroom West Chester Pa
Callie Gullickson Eye Patches
Nina Flowers
Coroner Photos Timothy Treadwell
✨ Flysheet for Alpha Wall Tent, Guy Ropes, D-Ring, Metal Runner & Stakes Included for Hunting, Family Camping & Outdoor Activities (12'x14', PE) — 🛍️ The Retail Market
Brother Bear Tattoo Ideas
Dontrell Nelson - 2016 - Football - University of Memphis Athletics
Rite Aid | Employee Benefits | Login / Register | Benefits Account Manager
How to Find Mugshots: 11 Steps (with Pictures) - wikiHow
Fredatmcd.read.inkling.com
Appsanywhere Mst
Dinargurus
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.