PowerShell Arrays
Handle zero, one and many results without changing the meaning of your script.
Documentation: Microsoft Learn
Overview
The scores example creates a three-item collection. Index zero selects its first item, so $scores[0] is 72. The last valid positive index is one less than the count.
Administrative queries rarely guarantee three results. A lookup may find none or one. Wrap a query in @(...) when subsequent code relies on collection operations, then check Count before choosing an item. An empty result should lead to a deliberate decision, not an unrelated null-method error later.
Do not use the first match as a substitute for identifying the correct record. If a task expects one server or user, validate that there is exactly one match and use a stable identity.
Repeatedly using += to grow an array can become expensive because new arrays are created. For substantial output, let the loop emit records and capture the loop result, or choose a collection designed for additions.
Inspect this example’s structure
Read the command and its supplied arguments. This example requires real PowerShell or its module; this diagram does not execute it.
$scores = 72, 85, 91
$scores[0]- Stage 1$scores
Positional values or no named parameters
What happens
Read the first, last and total number of scores. Then test an empty collection and a collection with one value in real PowerShell. A useful script handles all three shapes explicitly.
Worth remembering
An index identifies a position, not an object identity. Check collection size before relying on a position.
Primary documentation
Try it
Illustrative output · values vary by environment
Example reader
Inspect this page's example
Run supported commands against the practice data, or inspect the example without executing it.
Ready to inspect.
Creates a three-element array and reads the first element.
Show reference output
Illustrative output · values vary by environment
72
Practise this
Create a numeric array
Store 3, 5 and 8, in that order, in $numbers.
The sandbox is visible now. Sign in with Google only when you run or check a task; commands and temporary files are discarded when you leave.
Run a command to inspect its result.