POWERSHELL / CHAPTER 04

Collections, comparisons, and null

Intermediate

Avoid scalar-versus-array surprises in scripts.

By the end of this chapter

  • Normalize pipeline result shape with the array operator
  • Distinguish scalar and collection comparison behavior
  • Use null comparisons predictably

The idea

A command may emit zero, one, or many results, and assignment can therefore produce different shapes. The array subexpression operator @() collects results into an array, making Count and iteration easier to reason about when one consistent collection shape is required. Do not infer a collection’s cardinality from how a single value happens to display in the console.

Comparison operators also depend on the left operand. Comparing a scalar usually produces a boolean; comparing a collection with -eq returns matching elements. This can surprise code that expects a single truth value. For a null test, place $null on the left when checking whether a variable itself is null. PowerShell string comparisons are case-insensitive by default; use explicit case-sensitive variants when the contract requires them.

PowerShell example
$values = @(1, 2, 2, 3)
$matches = @($values -eq 2)
$matches.Count
("a" -ceq "A")
Result
2
False

Collection comparison returns both matching twos, so the collected result contains two elements. The case-sensitive comparison distinguishes the two letters.

Try it yourself

Collect all matching records into an array and report a count that remains correct for zero or one match.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

Which construction consistently collects zero, one, or many pipeline results into an array?