POWERSHELL / CHAPTER 10
Scope, shared objects, and module boundaries
AdvancedDistinguish changing a variable binding from mutating an object.
By the end of this chapter
- Trace local assignments in child scopes
- Recognize mutation through shared references
- Expose module behavior through deliberate public functions
The idea
PowerShell can find variables in an enclosing scope, but an ordinary assignment in a child scope normally creates or updates a local binding. Running a scriptblock with the call operator uses a child scope; dot-sourcing runs it in the current scope instead. These choices affect which names a helper can leave behind and whether a local assignment changes a caller-visible variable.
Scope does not automatically clone the objects referenced by variables. A child scope can obtain a reference to a mutable hashtable and change its contents even when it never rebinds the parent’s variable. Modules add a useful boundary for private implementation state and exported functions. Prefer explicit parameters and return values for ordinary communication, and document shared mutable state where it is intentional.
$value = 3
& { $value = 8; $value }
$value
$box = @{ Count = 1 }
& { $box.Count = 4 }
$box.Count8 3 4
The child assignment creates a local value binding. The hashtable mutation changes the shared object referenced by box.
Try it yourself
Refactor a helper that mutates a shared configuration hashtable so it returns an independent updated copy.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING