PowerShell Genie

PowerShell Arrays

Handle zero, one and many results without changing the meaning of your script.

Lesson 2 min read Windows PowerShell 5.1 and PowerShell 7

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]
  1. Stage 1$scoresPositional 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

    Microsoft Learn: arrays

    Try it

    Illustrative output · values vary by environment

    1PS> $scores = 72, 85, 91
    2PS> $scores[0]

    Example reader

    Inspect this page's example

    Fictional browser data when supported

    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.

      Review the lesson

      Keep going

      Next: PowerShell Hashtables
      Genie guidePowerShell Arrays

      Handle zero, one and many results without changing the meaning of your script.