liveBook · Manning

Scope

As explained in Learn PowerShell in a Month of Lunches: Fourth Edition, Covers Windows, Linux, and macOS

Scope is the region of a script or session in which a variable or other name is accessible.

Scope is the container that controls where PowerShell names—especially aliases, variables, and functions—can be accessed. The interactive shell is the global scope. Each running script creates a child script scope, and functions create their own private scopes. A scope lasts only while its work runs; when it ends, its contents disappear. section 19.7

When PowerShell cannot find a name in the current scope, it searches the parent scope and continues upward toward global scope. This explains why a script can see a value from its calling session, while values created inside the script normally stay there. For example, a script containing Write $x produces no output when $x has not been defined in either the script or global scope. section 19.7

Keep defaults inside a script

Setting $PSDefaultParameterValues at the command line affects commands and scripts run in that PowerShell session. Setting it inside a script limits those defaults to work performed by that script, so the surrounding shell and other scripts are not changed. section 26.6

Figure 19.5 Global, script, and function (private) scopes

Use the scope relationship figure to compare global, script, and private function scopes as nested parent and child containers. section 19.7

How Learn PowerShell in a Month of Lunches: Fourth Edition, Covers Windows, Linux, and macOS covers it

How deep it goes
Defines global, script, and private function scopes, explains parent lookup and lifetime, and defers detailed scoping rules.
Examples
Demonstrates $x across a script and shell session, and $PSDefaultParameterValues at command line versus script scope.
What it assumes
Builds from the PowerShell shell and scripts toward function scope and scoped variables.
What you can do after
Apply scope to keep script-specific defaults from affecting the surrounding shell or other scripts.
How it connects
Connects variables, aliases, functions, scripts, and default parameter values.

Also explained in

Compare how 21 books explain scope →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn PowerShell in a Month of Lunches: Fourth Edition, Covers Windows, Linux, and macOS. The section links point to the parts of the book it draws on.