How to Use a PowerShell Foreach Loop

The PowerShell Foreach statement is useful when working with collections of items. It can be used to run a command or a series of commands on each item in a collection. In this article, I will explain three different ways to use the Foreach keyword: the Foreach loop, the ForEach object cmdlet, and the ForEach method.

What is the PowerShell Foreach keyword for?

With PowerShell, there are several ways to process a collection of items. A collection can be created using commands such as B. can be retrieved from files get content for text files, Import CSV for files with comma separated values ​​and Import CliXML B. for hierarchical data stored in an XML file etc. The collection could also be the result of a command execution or a filtered result with the where object cmdlet.

If you need to take action against the members of this collection, use the For each -Statement that can be used as a loop, cmdlet, or method. In general, loops in PowerShell allow you to repeat a command or series of commands until a condition is met.

If you use one For each – Loop repeats operations until all items in the collection are processed. This reduces the size of the code and makes it more readable.

How to use a PowerShell foreach loop

A PowerShell For each Loop moves through the items in a collection, executing a command or series of commands on each of them. The syntax you need to use is pretty simple.

syntax

A PowerShell For each Loop starts with the keyword followed by parentheses with two variables: one for the collection and one for the current item being processed. The item variable is automatically created and assigned the value of the next item in the array before each iteration of the loop until all items are processed.

foreach ($<item> in $<collection>){<statement list>} 

At the end of the loop, the variable is not removed and contains the last item processed. The syntax continues with a script block that contains a command or list of commands to run on each item in the collection.

Read  Watch Arsenal vs. Liverpool: Live stream, score prediction, TV channel, how to watch, start time, odds

PowerShell foreach loop examples

To demonstrate how to a For each Loop, let’s take the following example: We take three services – WinRM, Spooler and BITS, which provide information about the display name, service name, status and startup type. The display name is on a separate line to simulate running multiple commands.

Without using a loop, the script would look like this:

# Service: WinRM
$ServiceWinRM = Get-Service -Name WinRM
Write-Host Processing Service: $ServiceWinRM.DisplayName -BackgroundColor DarkRed
Write-Host Service Name: $ServiceWinRM.Name is with status: $ServiceWinRM.Status and start type: $ServiceWinRM.StartType -BackgroundColor DarkGreen

# Service: Spooler
$ServiceSpooler = Get-Service -Name Spooler
Write-Host Processing Service: $ServiceSpooler.DisplayName -BackgroundColor DarkRed
Write-Host Service Name: $ServiceSpooler.Name is with status: $ServiceSpooler.Status and start type: $ServiceSpooler.StartType -BackgroundColor DarkGreen

# Service: BITS
$ServiceBITS = Get-Service -Name BITS
Write-Host Processing Service: $ServiceBITS.DisplayName -BackgroundColor DarkRed
Write-Host Service Name: $ServiceBITS.Name is with status: $ServiceBITS.Status and start type: $ServiceBITS.StartType -BackgroundColor DarkGreen 

This script returns the following result:

The result of our script without using a PowerShell foreach loop
The result of our script without using a foreach loop

If we use this first example and match it with the For each Loop syntax, our code would look like this:

$serviceList = Get-Service -Name "WinRM', 'Spooler', 'BITS'
foreach ($service in $serviceList) {
    Write-Host Processing Service: $service.DisplayName -BackgroundColor DarkRed
    Write-Host Service Name: $service.Name is with status: $service.Status and start type: $service.StartType -BackgroundColor DarkGreen
} 

By following the syntax of a For each loop, the variable containing the collection of services is called “serviceList”. The variable that contains the currently processed item is called “Service”.

Here’s what happens when we run this example in PowerShell:

  • The first iteration creates the variable “service” and assigns it the value “WinRM”. Then it processes the script block that provides information about display name on the first line, then name, status and launch type on the second line.
  • On the next iteration, the variable is assigned the value of the second item in the collection – Spooler, and the process repeats.
  • Finally, the variable “Service” is assigned the value of the service “BITS”. The script block runs and the loop completes while all items in the collection are processed.
We run our script with a foreach loop
We run our script with a foreach loop

As we explained, the variable holding the currently processed item in the collection is created on the first iteration of the loop. It remains available once the loop is complete.

Read  How to Skip Cutscenes and Dialogue
The variable containing the currently processed item in the collection remains available once the PowerShell foreach loop completes
The variable containing the currently processed item in the collection remains available after the loop completes

How to use the PowerShell-Foreach-Object cmdlet

Another way to process items in a collection is by using PowerShell foreach object cmdlet. There is often some confusion about this command as it is aliased with For eachwhich looks like the loop statement discussed in the previous section.

However, it is quite easy to distinguish the two: The For each Loop is always at the beginning of the statement, while the For each Alias ​​appears after a pipeline symbol and processes the collection that comes through the pipe.

That foreach object The command also has another alias that you can see here and there – %. The general rule in PowerShell is to avoid using aliases in your code, as this makes it difficult to read and can lead to confusion. Aliases can be handy to save time typing, but be careful when writing your code and try to make it more readable for the next person who reads it.

The PowerShell cmdlet Foreach-object has two aliases
The PowerShell cmdlet Foreach-object has two aliases

syntax

That foreach object Cmdlet processes the objects sent through the pipeline using the following (simplified) syntax:

<collection> | Foreach-Object -Process {<statement list>} 

Items from the collection are sent through the pipeline one at a time and processed in the Process parameter’s script block. There can be one or more lines of code.

Again, like in a foreach loop, we have a variable that holds the currently processed item. However, this time it’s a built-in variable (-$PSItem or $_) that’s only available until the pipeline completes.

PowerShell Foreach-Object cmdlet examples

If we keep the same example as before with the three services WinRM, Spooler and BITS, our code would look like this when using the Foreach-Object cmdlet:

Get-Service -Name 'WinRM', 'Spooler', 'BITS' | ForEach-Object -Process {
    Write-Host Processing Service: $_.DisplayName -BackgroundColor DarkRed
    Write-Host Service Name: $_.Name is with status: $_.Status and start type: $_.StartType -BackgroundColor DarkGreen
} 
We get the same end result when we use the PowerShell-Foreach-Object cmdlet
We get the same end result when we use the Foreach-Object cmdlet

The result is the same as in the previous examples. Here we use the built-in variable “$_”, but it would be the same if we used “$PSItem” since they are interchangeable.

Get-Service -Name 'WinRM', 'Spooler', 'BITS' | ForEach-Object -Process {
    Write-Host Processing Service: $PSItem.DisplayName -BackgroundColor DarkRed
    Write-Host Service Name: $PSItem.Name is with status: $PSItem.Status and start type: $PSItem.StartType -BackgroundColor DarkGreen
} 
We get the same result using the built-in variable '$PSItem'.
We get the same result using the built-in variable ‘$PSItem’.

In our scenario, the script block in the Process parameter of our Foreach Command example runs as many times as new objects are sent through the pipeline. There are also two parameters that you may find useful – begin and End. They are executed only once, at the start of processing and once processing is complete.

Read  2022 Shriners Children’s Open Thursday tee times, how to watch

These two parameters are useful when you want to lay the groundwork for running the collection. For example, at the beginning of your script you might want to remove old log files, create new log files, establish connections, provide user-friendly messages, etc. At the end, you might also want to clear out large variables. Closing connections, sending messages, etc.

So you need to use the syntax with these two parameters:

<collection> | Foreach-Object -Begin {<statement list>} -Process {<statement list>} -End {<statement list>}

In the context of our current example, let’s provide some start and end messages that include the current date and time in dark yellow color for readability:

Get-Service -Name 'WinRM', 'Spooler', 'BITS' | ForEach-Object -Begin { 
    Write-Host Starting Foreach-Object processing -BackgroundColor DarkYellow
} -Process {
    Write-Host Processing Service: $_.DisplayName -BackgroundColor DarkRed
    Write-Host Service Name: $_.Name is with status: $_.Status and start type: $_.StartType -BackgroundColor DarkGreen
} -End {
    Write-Host Completed Foreach-Object processing -BackgroundColor DarkYellow
} 
We've added start and end messages that include the current date and time
We’ve added start and end messages that include the current date and time

How to use the PowerShell ForEach method

The ForEach method is another alternative you can use to process a collection of objects with PowerShell. That’s how it works.

syntax

The ForEach method uses the following syntax:

<$collection>.ForEach ({<statement list>})

The PowerShell ForEach method processes all items in a collection to completion. Again like that foreach object cmdlet, refer to the current item in the collection using the built-in variables “$_” or “$PSItem”.

PowerShell ForEach method example

If we apply the ForEach method to our previous example, the syntax looks like this:

$serviceList = Get-Service -Name 'WinRM', 'Spooler', 'BITS'
$serviceList.ForEach({
    Write-Host Processing Service: $_.DisplayName -BackgroundColor DarkRed
    Write-Host Service Name: $_.Name is with status: $_.Status and start type: $_.StartType -BackgroundColor DarkGreen
}) 
As you can see, using the ForEach method, we get the same results as before
PowerShell ForEach method example

As you can see, we get the same results as before.

Conclusion

In this article, I’ve covered three different ways to use the Foreach statement in PowerShell, including the Foreach Loop, the ForEach Object cmdlet, and the ForEach Method. To go further, you can read our previous article on using the PowerShell ForEach Parallel option, as well as our general article on using PowerShell For Loop, While Loop, and other loops.

Leave a Comment

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