Chapter 22. Scope

 

This chapter covers

  • Understanding scope
  • Using scope
  • Using best practices

Scope is one of the most confusing things about PowerShell when you’re a newcomer, and even experienced gurus get tripped up by it from time to time. If you’re just using the shell as a shell—meaning you’re running commands and seeing the results onscreen—then scope won’t affect your life much. It’s when you start writing scripts, functions, and modules that scope comes into play.

22.1. Understanding scope

Scope is a form of containerization. Certain elements in PowerShell are considered scoped elements, and when you create one it exists only within the container, or scope, in which you created it. Generally speaking, it can only be used from within that scope as well. There are obviously a lot of rules and caveats around this, but we’re going to start with the basics and general realities and then diverge from there.

Take a look at figure 22.1, which illustrates the relationship between different kinds of scope.

Figure 22.1. Scopes can have both child and parent scopes, creating a hierarchical relationship.

There are three main types of scope in PowerShell. They all do exactly the same thing—the names just reflect the ways in which these scopes are created.

22.2. Observing scope in action

22.3. Dot sourcing

22.4. Manipulating cross-scope elements

22.5. Being private

22.6. Being strict

22.7. Summary