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, blackThe 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
EasyManage a list of maintenance tasks with an array.
- Create
$taskswithBackup,UpdateandReport. - Print
First:and the first task,Last:and the last task, andCount:and the number of tasks. - Add
Cleanupto the end and print the count line again. - Print all the tasks joined with a comma and a space.
- Print
Has report:and whether the array containsreport(written in lowercase).
Your script prints:
First: Backup
Last: Report
Count: 3
Count: 4
Backup, Update, Report, Cleanup
Has report: TrueTry it yourself
# Create the $tasks array, then print the lines
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in PowerShell Basics
5Project: Password Checker
Project OverviewLength Check