Chapter 5. Flow control in scripts
This chapter covers
- Conditional, looping, and switch statements
- Labels, break, and continue
- Flow control with cmdlets
- Statements as values
- Performance issues
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. Sooner or later, though, if you want to write significant programs or scripts, you must add custom looping or branch logic to your solution. Conditional statements enable your code to branch, dependent on tests you create. Loops execute a block of code one or more times depending on criteria you set—making your code shorter and more easily maintained. In this chapter, we’ll cover PowerShell’s take on the traditional programming constructs that all languages possess.
Flow-control behavior in PowerShell
As always, behavioral differences exist with the PowerShell flow-control statements (if, switch, and loop statements) of which new users should be aware. The most obvious difference is PowerShell typically allows the use of pipelines in places where other programming languages only allow simple expressions. This makes the PowerShell switch statement both a looping construct and a conditional statement—which is why it gets its own group.