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.
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:
This structure is ideal for performing bulk updates, checks, or actions against multiple Microsoft 365 objects without writing redundant lines of code.
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
}
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