Chapter 20. Basic scripts and functions

 

This chapter covers

  • Scripting execution scopes
  • Parameterizing your script
  • Outputting scripts
  • Filtering scripts
  • Converting a script to a function

You can accomplish many tasks in PowerShell by typing a command and pressing Enter in the shell console. We expect that most IT pros will start using PowerShell this way and will continue to do so most of the time. Eventually, you’ll probably get tired of typing the same thing over and over and want to make it more easily repeatable. Or you hand off a task to someone else and need to make sure that it’s done exactly as planned. That’s where scripts come in—and it’s also where functions come in.

20.1. Script or function?

Suppose you have some task, perhaps one requiring a handful of commands in order to complete. A script is a convenient way of packaging those commands together. Rather than typing the commands manually, you paste them into a script and PowerShell runs them in order whenever you run that script. Following best practices, you’d give that script a cmdlet-like name, such as Set-ServerConfiguration.ps1 or Get-ClientInventory.ps1. Think of a script as a “canned” PowerShell session. Instead of manually typing 10 or 100 commands, you put the same commands in a script and execute the script like a twenty-first-century batch file.

20.2. Execution lifecycle and scope

20.3. Starting point: a command

20.4. Accepting input

20.5. Creating output

20.6. “Filtering” scripts

20.7. Moving to a function

20.8. Filter construct

20.9. Summary