PowerShell For Loop

What is PowerShell For Loop?

A PowerShell for loop, often written as foreach, is a control structure used to execute a block of code repeatedly for each item in a collection—like a list of users, files, or mailboxes. It’s a core component of PowerShell scripting and is especially valuable in scenarios involving automation of repetitive administrative tasks.

In Microsoft 365 environments, it's commonly used to apply bulk changes to users, licenses, or settings with minimal manual effort.


How PowerShell For Loop Operates?

The most common syntax for looping through a list in PowerShell is:

foreach ($item in $collection) {
    # Action to perform on each $item
}

Here’s what happens:

  • $collection is a group of items—such as rows from a CSV file or a list of users.
  • PowerShell reads the collection item by item.
  • For each $item, it performs the code block inside the {}.
  • This continues until every item in the collection has been processed.

This structure is ideal for performing bulk updates, checks, or actions against multiple Microsoft 365 objects without writing redundant lines of code.

Usage Example

Here’s a practical example that uses the foreach loop to enable a batch of disabled Microsoft 365 user accounts:

$users = Import-Csv "users.csv"
foreach ($user in $users) {
  	Update-MgUser -UserId $user.UserPrincipalName -AccountEnabled $true
}
  • The script imports users from a users.csv file.
  • Then, it loops through each user and enables the account using Update-MgUser.
This kind of logic is the backbone of most bulk administrative scripts in Microsoft 365.

You can see the PowerShell for loop in action in this real-world scenario: Update Microsoft 365 User Attributes Script

Did You Know? Managing Microsoft 365 applications is even easier with automation. Try our Graph PowerShell scripts to automate tasks like generating reports, cleaning up inactive Teams, or assigning licenses efficiently.

Ready to get the most out of Microsoft 365 tools? Explore our free Microsoft 365 administration tools to simplify your administrative tasks and boost productivity.

© Your Site Name. All Rights Reserved. Design by HTML Codex