Module 5: Looping and Logical Constructs
If..else:
• IF.Else conditional constructs are used to execute script block based on condition
• If block executes, when condition true
• Else block executes, when condition is false
• ElseIf block executes, when previous condition false and current condition true
• IF. Else Syntax
If(Condition true)
{statement1;statement2 etc.}
Else
{statement1;statement2 etc.}
• IF.ElseIF Syntax
If(Condition1 true)
{Statemen1;Statement2 etc.}
ElseIf(Condition2 true)
{Statement3;Statement4 etc.}
Else
{Statement5;Statment6 etc.}
Examples:
Apple Software Solutions Page 1
Switch:
• Need to test against many comparison values
• If statement could be confusing
• Switch conditional block replaces many if statements
• Default comparison operator is –eq , we can compare against condition put in braces
• Default condition will be executed if no condition is true
• All applicable conditions will be executed
• If only one condition need to execute, use break statement
• We can provide case sensitive and wild card characters also
Examples:
Foreach-Object:
• ForEach-Object cmdlet executes block of statements for every single object in a pipeline
• $_ contains the current pipeline object
• "%" stands for ForEach-Object
Apple Software Solutions Page 2
Eg:
$a=1..10
Foreach($b in $a)
{
Write-output “$b”
}
While:
Statements in this block will executed until condition is true.
It is entry control loop
While($i –lt 10)
{
Write-host “$i”
}
Do..while:
Statements in this block will execute at least once. Block will execute until the while
condition is true
It is an Exit control block.
Do
{
Write-host “$i”
}while($i –lt 10)
Do..Until:
Statements in this block will execute at least once. Block will execute until the until
condition is true
It is an Exit control block.
Do
{
Write-host “$i”
}until($i –lt 10)
Apple Software Solutions Page 3
Forloop:
• Special type of While loops
• For loop not only evaluates not only one but three expressions
• Initialization: The first expression is evaluated when the loop begins
• Continuous Criteria: The second expression is evaluated before every iteration.If this
expression is $true, the loop will iterate
• Icrement: Third expression is likewise re-evaluated with every looping
• For loop becomes while loop if we ignore first and third expressions
• Syntax: For(Initialization;continuous criteria;Increment){//statemens}
Apple Software Solutions Page 4