Chapter 5. Scope

 

Like the previous chapter, this chapter may be a bit of a refresher. But because the concept of scope continues to trip people up, we feel it’s worth our time and yours to get on the same page. More than likely your toolmaking projects will be on the complex side, and if you don’t understand scope, you may end up with a bad tool.

5.1. What is scope?

Scope is a system of containerization. In some senses, it’s designed to help keep things in PowerShell from conflicting with one another. For example, if you ran a script that defined a variable named $x, you’d be pretty upset if some other script also used $x and somehow messed up your script. Scope is a way of building walls between and around different scripts and functions, so that each one has its own little sandbox to play in without fear of messing up something else.

There are several elements within PowerShell that are affected by scope:

  • Variables
  • Functions
  • Aliases
  • PSDrives
  • PSSnapins (but oddly not modules—so as things migrate mainly to modules and away from PSSnapins, this won’t matter much)

5.2. Seeing scope in action

5.3. Working out of scope

5.4. Getting strict with scope

5.5. Best practices for scope

5.6. Lab