PowerShell Tutorial – Loops (For, ForEach, While, Do-While, Do-Until)

Loops are an essential construct in any programming language as they enable a block of code to be repeatedly executed. This can be useful for iterating through items in an object or repeatedly performing an operation.

This tutorial covers the five types of loops that are provided in PowerShell – namely For, ForEach, While, Do-While, and Do-Until.

ForEach Loop

The foreach statement is very useful in PowerShell when you need  to loop through an array or loop through items in an object.

ForEach allows the loop to evaluate the number a certain type of objects in an array or parent object and loop through those objects. One thing to bear in mind is that a ForEach loop is that there is a performance penalty for this convenience.

The below example,  shows a ForEach Loop operating on a object, the code assigns the  object resulting from the Get-process cmdlet to a variable, and then iterates through the  process items in the object and displays the process name.

$Processes=get-process | select-object ProcessName
$i=1
foreach ($process in $Processes)
{write-host $i "Process Name is " $process.Processname;$i++; }

Foreach can also   iterate through an array – the below code lists all the elements in an array, does a cumulative addition, and computes the total:

$testarray=10,20,30,34,54,65,657,92
$i=0
$j=0
foreach ($element in in $testarray)
{ $j=$j+$element;
Write-host  "Cumulative Amount =" $j ;
$i++ }

For Loop

The For loop has three parts :
Continues…

One thought on “PowerShell Tutorial – Loops (For, ForEach, While, Do-While, Do-Until)

  1. Pingback: PowerShell Tutorial – CmdLets | Windows Server Help

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>