0
0
PowershellHow-ToBeginner · 3 min read

How to Use Array in PowerShell: Syntax and Examples

In PowerShell, you create an array by listing items inside @() brackets. You can access elements using their index with square brackets like $array[0]. Arrays help store multiple values in one variable for easy management.
📐

Syntax

An array in PowerShell is created by placing items inside @(). You can store any type of data inside an array. Access elements by their zero-based index using square brackets []. For example, $array[0] gets the first item.

  • @(): Defines an array.
  • $array[index]: Accesses element at position index.
  • Indexing starts at 0.
powershell
$array = @("apple", "banana", "cherry")
$firstItem = $array[0]
Write-Output $firstItem
Output
apple
💻

Example

This example shows how to create an array, add items, access elements, and loop through all items to print them.

powershell
$fruits = @("apple", "banana", "cherry")

# Add an item
$fruits += "date"

# Access the second item
Write-Output "Second fruit: $($fruits[1])"

# Loop through all fruits
foreach ($fruit in $fruits) {
    Write-Output "Fruit: $fruit"
}
Output
Second fruit: banana Fruit: apple Fruit: banana Fruit: cherry Fruit: date
⚠️

Common Pitfalls

One common mistake is forgetting to use @() when creating arrays, which results in a single value instead of an array. Another is using 1-based indexing instead of 0-based, which causes errors when accessing elements.

Also, appending items with += creates a new array each time, which can be slow for large arrays. For better performance, use [System.Collections.ArrayList] if you need many additions.

powershell
# Wrong: creates a single string, not an array
$wrongArray = "apple"  # This is a single string, not an array
Write-Output ($wrongArray.GetType().Name)

# Right: creates an array
$rightArray = @("apple", "banana", "cherry")
Write-Output ($rightArray.GetType().Name)
Output
String Object[]
📊

Quick Reference

ActionSyntaxDescription
Create array$array = @('item1', 'item2')Defines an array with items
Access element$array[0]Gets first item (index 0)
Add item$array += 'newItem'Appends item to array
Loop itemsforeach ($item in $array) { }Iterates over each element
Array length$array.LengthNumber of items in array

Key Takeaways

Use @() to create arrays and access elements with zero-based indexes.
Append items with += but consider ArrayList for many additions.
Always remember array indexes start at 0, not 1.
Loop through arrays with foreach to process each item easily.
Check array length with .Length property.