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.
Scope is a form of containerization. Certain elements in PowerShell are considered scoped elements, and when you create one it only exists 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.