0
0
PowerShellscripting~5 mins

Arrays in PowerShell

Choose your learning style9 modes available
Introduction
Arrays help you store many items together in one place. This makes it easy to work with lists of things like names or numbers.
You want to keep a list of files to process one by one.
You need to store multiple user names to check later.
You want to save daily temperatures for a week.
You have a group of commands to run in order.
You want to collect answers from a survey.
Syntax
PowerShell
$arrayName = @('item1', 'item2', 'item3')
# or
$arrayName = @()
$arrayName += 'newItem'
Use @() to create an array in PowerShell.
You can add items later using += operator.
Examples
Creates an array of fruits and prints the second item (banana).
PowerShell
$fruits = @('apple', 'banana', 'cherry')
Write-Output $fruits[1]
Starts with an empty array, adds one item, then prints it.
PowerShell
$emptyArray = @()
$emptyArray += 'firstItem'
Write-Output $emptyArray[0]
Prints the last item in the array (30) using negative index.
PowerShell
$numbers = @(10, 20, 30)
Write-Output $numbers[-1]
Array with one item, prints that item.
PowerShell
$singleItemArray = @('onlyOne')
Write-Output $singleItemArray[0]
Sample Program
This script shows how to create an array, print it, add a new item, and print it again.
PowerShell
# Create an array of colors
$colors = @('red', 'green', 'blue')

# Print all colors
Write-Output "Colors before adding new one:"
$colors

# Add a new color
$colors += 'yellow'

# Print all colors again
Write-Output "Colors after adding new one:"
$colors
OutputSuccess
Important Notes
Access array items by their position, starting at 0.
Adding items with += creates a new array internally, so avoid in large loops for performance.
Use arrays when you need to keep order and access items by index.
Summary
Arrays store multiple items in one variable.
Use @() to create arrays and += to add items.
Access items by index starting at zero.