How to Use ForEach Loop in PowerShell?

Like other programming languages, PowerShell has the concept of loops. The loop (cycle) allows you to execute several times a certain set of commands.

The ForEach loop allows you to iterate over the array’s values. Its task is to perform certain actions for all items of the array. Unlike regular for, it is used to iterate over objects in an array.

Hint. We remind you that PowerShell is an object-oriented programming language.

The ForEach loop has the following syntax:

ForEach ($item in $array){

Scriptblock

}

The $item variable inside the loop points to the current element of the $array.

For example, create a simple array and use the foreach loop to list all its values:

$PCs = "PCName1", "PCName2", "PCName3"

foreach ($PC in $PCs)

{

write-host $PC

}

 

foreach loop in powershell

In some programming languages, processing in order to process such an array you must perform 2 steps. First, you need to get the length of the array, and then perform an action for each element. In PowerShell, everything is simpler. You do not need to calculate the number of elements in the array. It just sequentially goes through all the elements.

Now try to get a list of files in a specific directory. Now, using the ForEach loop, display the file names and the creation date of each file:

$Files = (Get-ChildItem "C:PS*")

foreach ($File in $Files) {

write-host $File.name $File.CreationTime

}

As you can see, inside the ForEach loop you can access all the properties and methods of each object in the array.

powershell foreach

Let’s consider another example of using a For-Each loop in AD. For example, you need to copy a specific file to all computers in Denver (it is assumed that all computers joined to the Active Directory domain and placed in the same Organizational Unit):

# Get a list of active AD computers in OU Denver

$ADComps = Get-ADComputer -Filter {enabled -eq "true"}

# Now, using the ForEach loop, copy the file from the network shared folder to the root directory (C: drive) of each computer

$SourceFile= “denv-fs01docdistrmy.cfg”

foreach ($computer in $ADComps)

{

$Hostname = $Computer.Name

$TargetPath = "$HostnameC$"

Copy-Item $SourceFile $TargetPath -Force

}

Note that there is a ForEach-Object cmdlet (with the alias ForEach), and a ForEach loop. This may be misleading. The ForEach-Object command is most often used in pipelines. The ForEach loop cannot be used in the pipeline.

For example, the ForEach-Object command:

Get-Service | ForEach-Object {$PSitem.Name}

Or, using an alias:

Get-Service | ForEach {$PSitem.Name}

And now the ForEach loop:

$services= Get-Service

ForEach ($service in $services) {

write-host $service.displayname

}

The PowerShell understands by a general construction syntax when to use the ForEach cmdlet and when to use a loop.

One of the differences between foreach loop and a foreach cmdlet is the ability to use continue and break operators.

The continue statement allows you to skip the execution of the remainder part of a and immediately go to the next array element.

The break statement completely stops enumeration of elements in a loop. It is used, we are looking for a specific value and you need to exit the loop when it is found:

$num=0

$computers = 'PC1','PC2','Server1','PC3'

foreach ($computer in $computers) {

if ($computer -like '*Server*') {

break

}

$num++

}

$num

In this example, the loop stopped at third elements.

powershell foreach line in file

Three special variables are available in the ForEach loop::

  • $foreach.MoveNext() – go to next item;
  • $foreach.current – current item pointer;
  • $foreach.reset() – resets the iteration. Iterating will start anew, leading to an endless loop.

PowerShell ForEach loops have a very large scope. This helps in server administration, managing services, processes and files, operations with Active Directory objects, etc.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.