How to Use ForEach Loop in PowerShell?

Like other programming languages, PowerShell has the concept of loops. Earlier we already covered how to create a PowerShell script for looping through files and folders. 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 for each loop to list all its values:

$PCs = “PCName1”, “PCName2”, “PCName3”

Foreach ($PC in $PCs)

{

Write-host

In some programming languages, processing 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 array.

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 each loop and a for each cmdlet is the ability to use continue and break operators.

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

The break statement completely stops the 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 the third element.

Powershell for each line in the file

Three special variables are available in the ForEach loop:

  1. $foreach.MoveNext() — go to next item;
  2. $foreach.current — current item pointer;
  3. $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 *




Enter Captcha Here :