PowerShell Basics Level: Beginner Chapter 3: Think in Objects, Not Text

Arrays

An array holds a list of values in one variable. You can count them, read one by position, and process each one in turn.

Lesson 2 of 7 in Chapter 3: Think in Objects, Not Text. Previous step in this path: Variables. 3 learning objectives, 6 examples, and a knowledge check.

Start: what you will learn

An array holds a list of values in one variable. You can count them, read one by position, and process each one in turn.

Learning objectives

  • Create an array
  • Read an item by index and count the items
  • Loop over an array with foreach

Concept in simple words

What it is: An array is a list of values stored in one variable, so one name can hold many items in order, such as a list of computer names. Each item is called an element, and each element has a position, called an index. The array keeps the order you used when you created it, so the first item you wrote stays first, and the last item you wrote stays last.

Why it works

Why it exists: Most admin work is really list work, a list of computers, users, or files. An array keeps that list together, so you can count it, read one item by position, or repeat the same step for every item, instead of writing the same command once per item. Without an array, a list of ten computers would need ten separate variables, and a list of a hundred computers would be unworkable.

Why it works this way: PowerShell stores the list as one object that contains many values, and it gives that object two useful tools, a Count property that tells you how many items there are, and index notation, which is square brackets with a number, that reads one item by position. Because the list is one object, you can pass the whole list to a loop, to a pipeline, or to another command, and each item is still available in order.

Think of it like this

Think of it like this: An array is like a row of numbered lockers. Each locker holds one value, the lockers have numbers starting at zero, and the variable name is the name of the whole row. To get the first value, you open locker zero, not locker one. The number of lockers is the Count, and the locker number is the index, and mixing those two ideas up is the most common array mistake.

How it works, step by step

How it works, step by step: First, create an array with commas between values, for example $servers = "srv1", "srv2", "srv3". You can also write it with the array operator @(), for example @("srv1", "srv2"), which makes it clear that you mean a list, even if the list has only one item. The commas separate the values, and the quotes mark each value as text.

How it works, step by step, continued: Next, read the list. $servers.Count tells you how many items there are, and $servers[0] reads the first item, where the number in square brackets is the index, which is the position, starting at zero. Then, to do work for each item, use a foreach loop, which takes each item in turn, stores it in a loop variable, and runs the same block of code for that item.

How the index works, in detail: Counting starts at zero, so in a list of three items, the valid indexes are 0, 1, and 2. The last item is at index Count minus 1, so for a list with Count 3, the last index is 2. PowerShell also lets you count backwards with a negative index, so $servers[-1] reads the last item, and $servers[-2] reads the second last item. This is handy when you want the last item but you do not want to work out its number first.

How to read more than one item: You can read several items at once by listing several indexes, such as $servers[0, 2], which reads the first and third items. You can also read a range with the range operator .., such as $servers[0..1], which reads the first two items. The range operator builds the numbers 0 and 1 for you, and then each number is used as an index in turn.

How Count and Length relate: For an array, Count and Length give the same number, which is how many items the array holds. Count is the property you will see most often in PowerShell, because it also works on collections that are not strict arrays. A common confusion is to mix Count with the length of a single string, because "srv1".Length gives 4, which is how many characters are in that one text value, while an array of three names has Count 3, which is how many items are in the list.

What an array can hold: An array can hold values of the same kind, such as three text names, or it can hold mixed kinds, such as a text value, a number, and a true or false value, because PowerShell arrays are flexible about type. Mixed lists are allowed, but they make later steps harder to predict, because an operator may behave differently on text than on numbers. For clean work, keep one list to one kind of value when you can.

How a single item can surprise you: A command that returns many items gives you a list, but the same command may return only one item on another day, and then your variable may hold a single object rather than a list. Wrapping the result in @(), such as $items = @(Get-Service -Name Spooler), forces the result to be an array, even when it holds only one item. Since PowerShell 3.0, even a single object and an empty result have Count and Length properties, so $items.Count still works, but @() makes your intent clear and protects code that expects a list.

How to loop, and how it differs from the pipeline: The foreach statement, written as foreach ($server in $servers) { }, runs the block once per item, with $server holding the current item each time. This is different from ForEach-Object in a pipeline, which you will meet in the pipeline lesson, because ForEach-Object works on objects as they flow through the pipe, and uses $_ for the current object. Both repeat work per item, but the foreach statement works on a list you already hold, while ForEach-Object works on a stream of objects.

How to add an item: You can add an item with +=, such as $servers += "srv3", which gives you a new array that contains the old items plus the new one. For a short list this is clear and fine. For a very long list built inside a loop, += is slow, because PowerShell builds a new array each time. A cleaner pattern for a long list is to collect loop output, such as $results = foreach ($server in $servers) { "Checking $server" }, where PowerShell gathers every output from the loop into one array for you.

How to test membership and join a list: Use -contains to test whether a list holds a value, such as $servers -contains "srv2", which returns true or false. Note the order, because the list goes on the left and the value you are looking for goes on the right. Use -join to turn a list into one text value, such as $names -join ", ", which places a comma and a space between each item. Joining is useful when you want one readable line for a message or a report.

How to change one item: To change one item, assign by index, such as $servers[0] = "srv9", which replaces the first item and leaves the rest alone. Changing the loop variable inside a foreach loop does not change the array, because the loop variable is a copy for text and numbers in that step, not the locker itself. So if you need to change items, work by index, and then read the array back to confirm the change.

What happens when an index is out of range: If you ask for an index past the end of the list, such as $servers[99] on a list of three items, PowerShell returns nothing, rather than an error. That empty result can be misleading, because it looks like a missing value rather than a mistake. When a read gives you nothing, check .Count first, and check whether your index is smaller than Count, before you assume the data itself is missing.

Common mistakes, in plain words: The most common mistake is reading $servers[1] and expecting the first item, when index 1 is the second item. Another is forgetting @() when a result may hold only one item, and then writing code that assumes a list. A third is expecting an error for an out of range index, when PowerShell quietly returns nothing. A fourth is building a huge list with += inside a loop, which is slow. A fifth is changing the loop variable and expecting the array to change, when only an assignment by index changes an item.

How to spot an array problem: If your loop runs once when you expected many runs, check .Count, because you may hold one item rather than a list. If you get the wrong item, check whether you counted from zero or from one. If a read gives you nothing, check whether the index is past the end of the list. If a join or a count looks wrong, check whether you are counting items in a list or characters in one string.

Worked examples

Read each example in order. Each one explains its parts, then shows what to look for in the output.

Syntax

Syntax
$list = "a", "b", "c"

Example 1

Count gives the number of items. Index 0 gives the first item.

Example 1
$servers = "srv1", "srv2"
$servers.Count
$servers[0]

Illustrative output: 2 srv1

Example 2

The loop runs once per item, with $server holding the current item each time.

Example 2
foreach ($server in $servers) {
  Write-Output "Checking $server"
}

Illustrative output: Checking srv1 Checking srv2

Example 3

The first line stores three strings in one array, separated by commas. The second line uses -join, which is an operator that turns a list into one text value, with the value after -join placed between each item. Here that value is a comma plus a space, so the three separate items become one readable line.

Example 3
$names = "ana", "ben", "sam"
$names -join ", "

Illustrative output: ana, ben, sam

Example 4

The first line stores three names. The second line uses -1, which counts backwards from the end, so it reads the last item, sam. The third line uses the range 0..1, which reads the first two items, ana and then ben, each on its own line.

Example 4
$names = "ana", "ben", "sam"
$names[-1]
$names[0..1]

Illustrative output: sam ana ben

Example 5

The first line uses @() to force a list, even though it holds only one item. The second line confirms the list holds 1 item, and the third line reads that item by index 0. Without @(), a single result can behave like a single object rather than a list, so @() makes your intent clear.

Example 5
$one = @("srv1")
$one.Count
$one[0]

Illustrative output: 1 srv1

Example 6

The first line stores two names. The second line tests membership, with the list on the left and the value on the right, and returns true because srv2 is in the list. The third line adds srv3, and the fourth line confirms the list now holds 3 items.

Example 6
$servers = "srv1", "srv2"
$servers -contains "srv2"
$servers += "srv3"
$servers.Count

Illustrative output: True 3

Nothing on this page executes PowerShell code. The outputs above are illustrative only.

Common mistakes and troubleshooting

Read these before you try the examples, so you can spot the same problems in your own work.

  • Reading $servers[1] and expecting the first item. Indexing starts at zero.
  • Forgetting that an array with one item can behave differently from an array with many items. Check .Count when a result looks odd.
  • Reading $list[1] and expecting the first item, when indexing starts at zero, so $list[1] is actually the second item.
  • Expecting an error for an out of range index, such as $servers[99] on a short list, when PowerShell quietly returns nothing instead.
  • Building a long list with += inside a loop, which rebuilds the array each time and is slow. Collect loop output into a variable instead for long lists.
  • Changing the loop variable inside foreach and expecting the array to change. To change an item, assign by index, such as $servers[0] = "srv9".

Knowledge check

Knowledge check

In $list = "a", "b", "c", what is $list[1]?

Pick one answer. Feedback appears right away, and you can try again.

Remember this and next step

Remember this: An array is a list in one variable, counting starts at zero, .Count tells you how many items there are, -1 reads the last item, .. reads a range, @() forces a list even for one item, a foreach loop does the same work for each item, -contains tests membership, -join turns a list into one line of text, += adds an item for short lists, and an out of range index quietly returns nothing instead of an error.

Next step: The pipeline and parameter binding