Adding some logic
PowerShell would not be very useful if scripts were limited to running one command after another without any logic. As expected from a modern language, PowerShell includes a full complement of control structures to allow you to vary the execution in just about any way you'd like. We will briefly introduce the most common control structures.
Conditional logic (IF)
The most simple logic statement is the If
statement. The If
statement allows you to have some code executed, if and only if a particular condition is met. In its simplest form, the If
statement includes a condition in parentheses and a scriptblock to be executed when the condition is true:
If there is another condition that should be executed if the first condition is false, you can include an Else
clause:
If you have multiple conditions to test, there is an ElseIf
clause as well. Here's an example of its use:
Looping logic
The most common way to loop in PowerShell is the ForEach
statement. ForEach
causes a scriptblock...