Chapter 6. Flow control in scripts

 

This chapter covers:

  • 6.1 The conditional statement
  • 6.2 Looping statements
  • 6.3 Labels, break, and continue
  • 6.4 The switch statement
  • 6.5 Flow control using cmdlets
  • 6.6 Statements as values
  • 6.7 A word about performance
  • 6.8 Summary

I may not have gone where I intended to go, but I think I have ended up where I needed to be.

Douglas Adams, The Long Dark Tea-Time of the Soul

Previous chapters showed how you can solve surprisingly complex problems in PowerShell using only commands and operators. You can select, sort, edit, you and present all manner of data by composing these elements into pipelines and expressions. In fact, commands and operators were the only elements available in the earliest prototypes of PowerShell. Sooner or later, though, if you want to write significant programs or scripts, you must add custom looping or branch logic to your solution. This is what we’re going to cover in this chapter: PowerShell’s take on the traditional programming constructs that all languages possess.

The PowerShell flow-control statements and cmdlets are listed in figure 6.1, arranged in groups.

Figure 6.1. The PowerShell flow-control statements

We’ll go through each group in this chapter. As always, behavioral differences exist with the PowerShell flow-control statements that new users should be aware of.

6.1. The Conditional Statement

6.2. Looping Statements

6.3. Labels, Break, and Continue

6.4. The Switch Statement

6.5. Flow Control Using Cmdlets

6.6. Statements as Values

6.7. A Word About Performance

6.8. Summary

sitemap