Powershell conditional and looping statements
Introduction
The following examples will provide how to use the conditional statements(if, elseif, else, switch) and looping statements(for, while, do/while, foreach, foreach-object, where-object). Though these are very common techniques used in any programming language, the syntax is what matters here.
Examples in this post gives understanding of the usage and syntax.
if / elseif / else
Following example shows how if/elseif/else conditional statement is used. The if condition will execute the block if the condition is satisfied.
Ex:
$myVar = 21
if($myVar -eq 1)
{
write-host “myVar value is 1”
}
elseif($myVar -eq 2)
{
write-host “myVar value is 2”
}
else
{
write-host “This is default”
}
Output: This is default
Switch
Following example shows how switch statement is used.
Ex:
$myVar = 21
switch($myVar)
{
21 { “myVar value is 21”;break; }
22 { “myVar value is 22”;break; }
Default {“This is defalut value”}
}
Output: myVar value is 21
Switch statement can also be used to compare case sensitive values as in the following example.
Ex:
$myVar = “Test”
switch -CaseSensitive ($myVar)
{
“test” { “myVar value is test”;break; }
“Test” { “myVar value is Test”;break; }
Default {“This is defalut value”}
}
Output: myVar value is Test
for
Ex:
for($i = 1; $i -le 5; $i ++)
{ write-host “Current Number is ” $i }
Output:
Current Number is 1
Current Number is 2
Current Number is 3
Current Number is 4
Current Number is 5
while
Ex:
$i = 1;
while($i -le 2)
{
write-host “Current Number is ” $i
$i++;
}
Output:
Current Number is 1
Current Number is 2
do/while
Ex:
$i = 1;
do
{
write-host “Current Number is ” $i;
$i++
}
while($i -le 2)
Output:
Current Number is 1
Current Number is 2
foreach
Ex:
$myItems = 1,2,3
foreach($iVariable in $myItems)
{
write-host $iVariable
}
Output:
1
2
3
ForEach-Object
ForEach-Objct is an alias to foreach statement.
In the following example observe how to use automatic variable ‘$_’ to represent the current object.
All the following examples have same output
Ex 1:
$myItems = 1,2,3
$myItems | ForEach-Object {$_}
Ex 1:
$myItems = 1,2,3
$myItems | foreach {$_}
Output:
1
2
3
Where-Object
Where-Object is same as foreach but with a condition in it. If the condition is statisfied, it executes the statements.
Ex:
$myItems = 1,2,3
$myItems | Where-Object {$_ -lt 3}
Output:
1
2
Conclusion
The above examples provide good understanding on conditional and looping statements. These are very much important basics as we go on with advance examples and techniques in powershell with SharePoint 2010.
References:
using variables, arrays and hashtables
using arthimatic operators, assignment operators and comparision operators
using logical operators and redirection operators
April 22, 2012
В·
Adi В·
No Comments
Tags: PowerShell 2.0, Powershell Conditional Statements, Powershell looping statements, SharePoint 2010 В· Posted in: Conditional Statements, Operators, Powershell, Sharepoint 2010
Leave a Reply