Skip to content

Difference between ForEach and ForEach-Object PowerShell

You can use the ForEach statement and ForEach-Object cmdlet in your PowerShell scripts. They both use loops to iterate through the data, but these loops are different. In this article, you will learn the difference between Foreach and ForEach-Object in PowerShell.

ForEach vs. ForEach-Object PowerShell

You can use the ForEach statement or ForEach-Object cmdlet in PowerShell to iterate through a collection of objects. The biggest difference is that you can use the ForEach statement at the beginning of a PowerShell command line, while the ForEach-Object cmdlet can only be used after a pipeline.

The table below shows the differences between the ForEach and ForEach-Object.

ForEachForEach-Object
Beginning of a command lineAfter a pipeline
FastSlow

After reading this article, you should know how to use ForEach and ForEach-Object in PowerShell. If you already have an array, use the ForEach statement. If you have a pipeline input and want to export the results, use the ForEach-Object.

PowerShell Foreach statement

The ForEach statement is used to iterate through a collection of data, such as a list of items, mailboxes, or users.

How to create an Array in PowerShell

An array is a collection of objects (members). Usually, you use the array to group or bind one or more objects. When you use the ForEach statement, it will refer to each member in the array.

Some examples of array objects:

  • Users
  • Exchange Online mailboxes
  • A row in a file
  • Operating system process

An array can be a specific object or a subset of specific objects. For example, all the Exchange Online mailboxes are an array, which is a specific object. If you only want the user mailboxes, they can also be an array, which is a subset of the Exchange Online mailboxes.

array and subset of an array in ForEach vs ForEach-Object PowerShell

There are different methods you can use to create an array:

  1. Use a basic PowerShell command and use an array. For example, each PowerShell cmdlet that starts with Get.
  2. Information data from a specific format, such as a CSV file, can also be an array. When you open the CSV file, it has rows and columns, where each row represents an array of members. Each column represents a member property.
  3. Using a group is actually an array. A group serves as a logical container that contains group members, which is an array.
  4. If you manually write each member separated by a comma character, you also create an array of multiple users.

Use PowerShell command to create an Array

By default, when you use the Get PowerShell cmdlet, it will create an array. When we use PowerShell cmdlets such as Get-Mailbox, we are asking for information about a very specific object type, Exchange mailboxes. PowerShell automatically creates an array space and fills the array store with information about all the existing Exchange mailboxes. Then you can export the array information to a file or pipe the information to another PowerShell command.

In our example, we will use the specific property RecipientTypeDetails. If you only want to get a specific subset or group of Exchange Online mailboxes, like user mailboxes, you need to create an array. We will use the -Filter search parameter in the PowerShell command.

The below PowerShell command will get a list of all the user mailboxes in Exchange Online.

Get-Mailbox -ResultSize Unlimited -Filter { (RecipientTypeDetails -eq "UserMailbox") }

You can also create a PowerShell command with another -Filter search parameter.

Another example is to get a list of all the Exchange Online users but add a filter only to get the users from the IT department.

Get-User -ResultSize Unlimited -Filter 'Department -eq "IT"'

Let’s see how to use these PowerShell commands as an array in the next step.

Use PowerShell variable to create an Array

The variable is an essential component often used with the PowerShell ForEach statement. The PowerShell variable serves as a logical container and stores the information data of the array members.

Go through these steps to define a PowerShell variable:

  • Use the $ symbol to display a variable.
  • Define the variable name that relates to the data. Variable names are not case-sensitive. Variable names can include spaces and special characters, but these are difficult to use and should be avoided.
  • Use the PowerShell Get command to fetch data about specific objects. The output from the PowerShell command will be stored in the variable.

A PowerShell variable syntax example.

$ExchangeMailboxes = Get-Mailbox -ResultSize Unlimited

In the above example, we have a variable named $ExchangeMailboxes that stores the information from the Get-Mailbox PowerShell cmdlet.

When we run the $ExchangeMailboxes variable, it will show all the mailboxes.

$ExchangeMailboxes

PowerShell ForEach loop with an Array

Sometimes you must perform a bulk operation using PowerShell commands on a group of objects (array).

If you need to run a task on an array many times, it’s best to combine the Foreach statement with a variable to store the array data (members).

Define the PowerShell command using ForEach loop with variables:

  • Name the variable to store the results of the Get PowerShell command.
  • Start the ForEach statement, followed by parenthesis ( ). Define the name of another variable, like $Member, to represent each member in the array.
  • The PowerShell command to perform the operation to the array must be enclosed in braces brackets { }. When you use a ForEach statement, it will execute the PowerShell command separately for each member in the array.

The PowerShell ForEach syntax example.

$VariableName = Get PowerShell command
ForEach ($Member in $VariableName) {
    #PowerShell command perform the operation
}

We will use the above PowerShell ForEach syntax in the next step.

Use ForEach loop to specify Array objects

An array is a collection of objects, such as all users or members. Each user within that array is an array member.

Array and array member objects in ForEach vs ForEach-Object PowerShell

We will show you two methods to show an array member.

Method 1: View specific array member

In our example, the variable $ExchangeMailboxes represents the array, but the variable $ExchangeMailbox represents each member in the array.

Run the below PowerShell script to get a list of all array members.

$ExchangeMailboxes = Get-Mailbox -ResultSize Unlimited
ForEach ($ExchangeMailbox in $ExchangeMailboxes) {
    $Member
}

To view a specific array member, you can show what is stored in the variable $ExchangeMailboxes. Run the below PowerShell command to view the first array member.

$ExchangeMailboxes[0]

The PowerShell output shows the below results.

Name                      Alias       Database           ProhibitSendQuota    ExternalDirectoryObjectId
----                      -----       --------           -----------------    -------------------------
0de964ae-f09a-4e65-bc8c-… Adam.Mackay EURPR02DG610-db026 99 GB (106,300,440,… 0de964ae-f09a-4e65-bc8c-cbeac2745e4c

Run the below PowerShell command to view the second array member.

$ExchangeMailboxes[1]

The PowerShell output results.

Name                      Alias       Database           ProhibitSendQuota    ExternalDirectoryObjectId
----                      -----       --------           -----------------    -------------------------
0de964ae-f09a-4e65-bc8c-… Adam.Mackay EURPR02DG610-db026 99 GB (106,300,440,… 0de964ae-f09a-4e65-bc8c-cbeac2745e4c

Method 2: Use the write-host to show all array members

You can add a write-host to the $member variable in line 3.

Run the below PowerShell script to get a list of all the array members.

$ExchangeMailboxes = Get-Mailbox -ResultSize Unlimited
ForEach ($ExchangeMailbox in $ExchangeMailboxes) {
    Write-host "This is one of the array members" -$ExchangeMailbox
}

The PowerShell output shows a list of all the members with an Exchange Online mailbox.

This is one of the array members -Adam Mackay
This is one of the array members -Amanda Hansen
This is one of the array members -Blake Martin
This is one of the array members -Brenda Smith
This is one of the array members -Brian Mill
This is one of the array members -Carl Hawk
This is one of the array members -Carol Piper
This is one of the array members -Chris Lucas
This is one of the array members -Diana Baker
This is one of the array members -Frank Olsen
This is one of the array members -Julia Wood
This is one of the array members -Ken Walker
This is one of the array members -Laura Terry
This is one of the array members -Owen Terry
This is one of the array members -Projector 21
This is one of the array members -RoomMail 8
This is one of the array members -Stephen Hunter
This is one of the array members -Stephen Lambert

Specify Identity of specific array member

With PowerShell we can get each member of an array, but now we want to specify their identity.

To specify the identity of each member in an array, you should use the following PowerShell syntax.

$ExchangeMailbox.Identity

The variable $ExchangeMailbox is the array member, and the Identity is the object property.

There are multiple object identities in the Exchange Online mailbox. The Identity parameter specifies the Exchange Online mailbox, and you can use one of these values.

  • Name
  • Alias
  • Distinguished name (DN)
  • Canonical DN
  • Domain\Username
  • Email address
  • GUID
  • LegacyExchangeDN
  • SamAccountName
  • User ID or user principal name (UPN)

Array members and types in PowerShell

There are four different types of relations you can use in PowerShell:

  • Single user to another user
  • Single user to multiple users
  • Multiple users to multiple users
  • Multiple users to a single user

We will show you two of these examples with the ForEach statement.

Single user to multiple users using ForEach

In our example, the user Ken Walker is the Exchange Online administrator. We want to assign Full Access permission to all the existing user mailboxes.

You need to create a PowerShell script that consists of these parts:

  1. First, you need to define a variable named $UserMailboxes to get all the user mailboxes in Exchange Online.
  2. Then you will add an additional variable named $UserMailbox to represent each member in the user mailboxes array.
  3. Lastly, you will create a PowerShell command to assign the user Ken Walker with Full Access permission to each of the user mailboxes. To refer to an array member, you need to use the variable of the array, followed by the identity, which will look like $UserMailbox.Identity. Combining these two parts lets you identify each array member individually in the ForEach loop process in PowerShell.

The PowerShell syntax example.

$UserMailboxes = Get-Mailbox -ResultSize Unlimited -Filter { (RecipientTypeDetails -eq "UserMailbox") }
ForEach ($UserMailbox in $UserMailboxes) {
    Add-MailboxPermission -Identity $UserMailbox.Identity -User "Identity" -AccessRights FullAccess
}

Run the below PowerShell script.

$UserMailboxes = Get-Mailbox -ResultSize Unlimited -Filter { (RecipientTypeDetails -eq "UserMailbox") }
ForEach ($UserMailbox in $UserMailboxes) {
    Add-MailboxPermission -Identity $UserMailbox.Identity -User "Ken.Walker@m365info.com" -AccessRights FullAccess
}

It will assign the user Ken Walker with Full Access permission on all user mailboxes.

Multiple users to a single user using ForEach

In our example, the users from the IT department want Full Access permission to a single mailbox (Amanda.Hansen@m365info.com).

The PowerShell script consists of these parts:

  1. In the first part, we define the variable named $ITmembers to get the users from the IT department.
  2. Then you will add an additional variable named $ITmember to represent each member in the IT array.
  3. Lastly, you will create a PowerShell command to assign the users from the IT department with Full Access permission to a single mailbox. To refer to an array member, you need to use the variable of the array, followed by the identity, which will look like $ITmember.Identity. Combining these two parts lets you identify each array member individually in the ForEach loop process in PowerShell.

See the below PowerShell syntax.

$ITmembers = Get-User -ResultSize Unlimited -Filter 'Department -eq "IT"'
ForEach ($ITmember in $ITMembers) {
    Add-MailboxPermission -Identity "Identity" -User $ITmember.Identity -AccessRights FullAccess
}

Run the below PowerShell script.

$ITmembers = Get-User -ResultSize Unlimited -Filter 'Department -eq "IT"'
ForEach ($ITmember in $ITMembers) {
    Add-MailboxPermission -Identity "Amanda.Hansen@m365info.com" -User $ITmember.Identity -AccessRights FullAccess
}

It will assign each user from the IT department Full Access permission on a single (Amanda.Hansen@m365info.com) mailbox.

PowerShell ForEach-Object cmdlet

The ForEach-Object cmdlet performs an operation on each item in a collection of input objects. You need to use the InputObject parameter and specify the input objects or create a pipeline as an input to the cmdlet.

The ForEach-Object PowerShell cmdlet syntax.

Get-Mailbox -ResultSize Unlimited | ForEach-Object {
    #PowerShell command to perform operation on each object
}

There are two different ways to use the ForEach-Object command.

Use the ForEach-Object in script block

You can use a script block to specify the operation you want to perform. In the script block, you must use the $_.variable to represent the object and define it in braces brackets { }.

For example, you want to get the UserPrincipalName of all the Exchange Online mailboxes.

See the ForEach-Object PowerShell syntax in a script block.

Get-Mailbox -ResultSize Unlimited | ForEach-Object {$_.UserPrincipalName}

It will show a list of all the UserPrincipalName in Exchange Online mailboxes.

Use ForEach-Object in operation statement

You can also write an operation statement, which is easier to understand. Since there is no variable to use, you only need to provide an input to the ForEach-Object cmdlet.

For this example, we will also get the UserPrincipalName of all mailboxes.

See the ForEach-Object PowerShell cmdlet syntax in an operation statement.

Get-Mailbox -ResultSize Unlimited | ForEach-Object UserPrincipalName

That’s it!

Read more: How to use Logical Operators in PowerShell »

Conclusion

You learned how to use ForEach and ForEach-Object in PowerShell. It’s faster to use the ForEach statement to iterate through a collection of data. The ForEach-Object cmdlet performs an operation on a collection of input objects that come from a pipeline, which is more flexible to use but slower.

Did you enjoy this article? You may also like How to use Comparison Operators in PowerShell. Don’t forget to follow us and share this article.

o365info Team

o365info Team

This article was written by our team of experienced IT architects, consultants, and engineers.

This Post Has 0 Comments

Leave a Reply

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