liveBook · Manning

Collection

As explained in Learn PowerShell Scripting in a Month of Lunches, Second Edition: Write and organize scripts and tools

A collection is a group of objects treated as a single set of values for operations such as membership testing.

A collection groups objects so a script can test membership or process each value in turn. In PowerShell, arrays are a common collection form. section 5.1.2 section 5.3

Use collections for two common scripting tasks:

  • Check whether an array contains a value with -contains, or place the value on the left and use -in. section 5.1.2
  • Enumerate items with ForEach; the loop assigns one object at a time to a variable and exits after the collection is exhausted. section 5.3
  • Prefer readable singular and plural variable names, such as $name and $names, while following command parameter conventions when necessary. section 5.3
$array = @("one", "two", "three")
$array –contains "one"
$array –contains "five"
"two" –in $array
"bob" –in $array

Run membership tests against a three-item array to see which values belong to the collection. section 5.1.2

$services = Get-Service –name bits,lanmanserver,spooler
Foreach ($service in $services) {
  Restart-service $service –passthru
}

Process service objects one at a time with ForEach and restart each service with pass-through output. section 5.3

How Learn PowerShell Scripting in a Month of Lunches, Second Edition: Write and organize scripts and tools covers it

How deep it goes
Explains arrays, membership operators, enumeration, and naming practice through runnable examples, without covering collection internals.
Examples
Uses server lists, names read from a file, numeric ranges, and service objects.
What you can do after
Apply it via PowerShell to test membership and process each object in turn.
How it connects
Connects collections with arrays, membership operators, ForEach loops, and ForEach-Object.

Also explained in

Compare how 16 books explain collection →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn PowerShell Scripting in a Month of Lunches, Second Edition: Write and organize scripts and tools. The section links point to the parts of the book it draws on.