Summary
This chapter explored the different conditional and looping statements available in PowerShell.
The if
statement allows statements to be run when a condition is met and may be extended to test several conditions with elseif
.
The switch
statement has similarities with if
, a comparison of one value against another. However, switch
can test many individual cases expressed in a concise manner, allows more than one case to apply to a value, and can operate on an array.
Looping is a vital part of any programming language and PowerShell is no exception. The foreach
loop is perhaps the most used, allowing repeated code to be enclosed and executed against several objects. The foreach
loop keyword can often be replaced with the ForEach-Object
command (or vice versa) depending on circumstances, but the two should not be confused.
for
loops are more complex but offer a great deal of flexibility for any operation based on a numeric sequence. while
and do
loops can be used...