Powershell Scripting Tutorial
Introduction Tools required for Powershell First Powershell script Interacting with userSpecial characters in Windows Powershell scriptingArrays String manipulation Conditional statements Looping statements Passing arguments Passing named arguments Exit status of the script Writing functionsLoops in windows powershell scripting
We have below looping statements in Powershell- C-Style for loop
- foreach
C-style for loop
You can use below syntax to create a for loop.
for ($i=1;$i -lt 10; $i++) {
echo “Printing $i”
}
foreach (also called as % and foreach-object) loop
You can use foreach loop to iterate through arrays and collections.
foreach ($city in $cities) {
echo “City is $city”
}
You can also use foreach loop to work on piped data as shown in below example. Here we are printing length of each line in the file.
> Get-Content cities.txt | foreach {echo $_.length}
While Loop
Powershell also provides while loop and do..while loop constructs just like C language. Below example shows the simple while loop. It will print values from 0 to 6 and then exit.
$i=0
while($true)
{
echo $i
if ($i-gt 5){
break
}
$i = $i + 1
}
Do….While Loop
Powershell also provides do..while loop construct just like C language. Below example shows the simple do….while loop. It will print values from 0 to 6 and then exit.
$i=0
do
{
echo $i
if ($i-gt 5){
break
}
$i = $i + 1
}while($true)
Do…Until Loop
You can use do until loop using below syntax. Below script will print from 0 to 5 and then exit.
$i=0
do
{
echo $i
$i = $i + 1
}until($i -gt 5)
Web development and Automation testing
solutions delivered!!