Menu
CoddyTech

Arrays

Part of the PowerShell Basics section of Coddy's PowerShell journey. Lesson 16 of 28.

An array holds several values in order. Write it with @( ), or list the values with commas:

$colors = @("red", "green", "blue")
Write-Output $colors[0]
Write-Output $colors[-1]
Write-Output $colors.Count
$colors += "black"
Write-Output ($colors -join ", ")
red
blue
3
red, green, blue, black

The index starts at 0, and -1 counts from the end. An index past the end gives $null, so $colors[3] on a 3-item array prints nothing. += adds an item and -join turns the array into one string.

$colors -contains "Green" is True when an item equals the value, ignoring case. -split does the opposite of -join: "a b c" -split " " gives the array a, b, c.

challenge icon

Challenge

Easy

Manage a list of maintenance tasks with an array.

  1. Create $tasks with Backup, Update and Report.
  2. Print First: and the first task, Last: and the last task, and Count: and the number of tasks.
  3. Add Cleanup to the end and print the count line again.
  4. Print all the tasks joined with a comma and a space.
  5. Print Has report: and whether the array contains report (written in lowercase).

Your script prints:

First: Backup
Last: Report
Count: 3
Count: 4
Backup, Update, Report, Cleanup
Has report: True

Try it yourself

# Create the $tasks array, then print the lines
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in PowerShell Basics