Performing Bulk User Management with PowerShell

Earn 25 points (50 with Pro) in two steps

  1. ① Read through the lesson — each section gets a ✓ as you scroll through it.
  2. ② When every section has a ✓, tap Complete lesson.

0 of 11 read · keep scrolling

✦ See fewer ads and earn double points — 50 a lesson instead of 25 — with Pro

Lesson: Performing Bulk User Management with PowerShell

Introduction: The Necessity of Automation in Microsoft 365

Managing a Microsoft 365 tenant is a task that scales poorly when handled manually. In a small environment with ten or twenty employees, the Microsoft 365 Admin Center interface is perfectly adequate for creating accounts, assigning licenses, and adding users to security groups. However, as organizations grow, the limitations of the graphical user interface (GUI) become apparent. Performing repetitive tasks like onboarding fifty new hires at once or updating the department attribute for an entire division can consume hours of valuable administrative time if done via point-and-click methods.

Bulk user management is the practice of using scripts or automated tools to process multiple user objects simultaneously. By utilizing the Microsoft Graph PowerShell SDK, administrators can transform complex, multi-step tasks into single, executable commands. This not only saves time but also significantly reduces the risk of human error, such as typos in email addresses or incorrectly assigned licensing bundles. Mastering these techniques is not just about efficiency; it is about establishing a repeatable, reliable process that ensures your tenant remains organized and compliant as your workforce evolves.

In this lesson, we will explore the mechanics of bulk management. We will move beyond basic account creation to cover licensing, group membership, and attribute modification. By the end of this guide, you will have the knowledge required to handle large-scale administrative changes with precision, safety, and confidence.


Not read yet

Prerequisites and Environment Setup

Before you can execute any bulk management tasks, your administrative workstation must be properly configured. Microsoft has transitioned from the older MSOnline and AzureAD modules to the Microsoft Graph PowerShell SDK. This is the modern, supported way to interact with your tenant, and it is essential that you familiarize yourself with this framework.

Installing the Required Modules

To get started, you need to install the Microsoft Graph PowerShell module. Open your PowerShell console as an Administrator and execute the following command:

Install-Module Microsoft.Graph -Scope CurrentUser

Once installed, you must connect to your tenant with the appropriate permissions. It is a best practice to use the principle of least privilege, meaning you should only request the scopes necessary for the tasks you intend to perform. For bulk user management, you will typically need User.ReadWrite.All, Directory.ReadWrite.All, and GroupMember.ReadWrite.All.

Connect-MgGraph -Scopes "User.ReadWrite.All", "Directory.ReadWrite.All"

Note: Always ensure your PowerShell execution policy allows for running scripts. You can check this by running Get-ExecutionPolicy. If it is set to Restricted, you may need to set it to RemoteSigned using Set-ExecutionPolicy RemoteSigned -Scope CurrentUser to allow your own scripts to run.


Not read yet

Preparing Your Data: The CSV Workflow

The most common way to handle bulk operations is by using a Comma Separated Values (CSV) file. A CSV file acts as your source of truth. It contains the data points required for your users, such as UserPrincipalName, DisplayName, Department, and UsageLocation.

Structuring Your CSV

Your CSV file should have headers that match the variables you intend to use in your script. For example, a file named new_users.csv might look like this:

DisplayName,UserPrincipalName,Department,UsageLocation,Password
John Doe,[email protected],Sales,US,TempPass123!
Jane Smith,[email protected],Marketing,US,TempPass123!

When creating these files, always use a plain-text editor or a spreadsheet application that allows for clean CSV exports. Ensure there are no hidden characters or trailing spaces, as these can cause failures during the import process.


Bulk User Creation

Creating users in bulk is the foundational task of administrative automation. Instead of filling out a form twenty times, you create a script that iterates through your CSV file and creates each user object in a single pass.

The Logic of the Script

The process involves importing the CSV into a PowerShell variable using Import-Csv. Once the data is in memory, you use a foreach loop to process each row. Within the loop, you call the New-MgUser command, mapping the properties from the CSV row to the parameters required by the cmdlet.

Practical Example: Creating Users

# Import the CSV data
$Users = Import-Csv -Path "C:\Temp\new_users.csv"

# Iterate through each row
foreach ($Row in $Users) {
    # Create the user object
    New-MgUser -DisplayName $Row.DisplayName `
               -UserPrincipalName $Row.UserPrincipalName `
               -MailNickname ($Row.UserPrincipalName.Split('@')[0]) `
               -UsageLocation $Row.UsageLocation `
               -AccountEnabled `
               -PasswordProfile @{Password = $Row.Password; ForceChangePasswordNextSignIn = $true}
    
    Write-Host "Created user: $($Row.DisplayName)" -ForegroundColor Green
}

This script is simple yet powerful. Notice the use of the PasswordProfile parameter; it is a dictionary object that allows you to set the initial password and enforce a password change upon the first login. This is a crucial security step that should never be skipped.

Callout: Why Use MailNickname? The MailNickname property is a required attribute for user objects in Microsoft 365. It represents the alias of the user's email address. If you do not provide it, the New-MgUser command will fail. By using the split method on the UPN, we can dynamically generate this alias based on the part of the email address before the @ symbol.


Not read yet

Bulk Licensing Operations

Assigning licenses is often the most tedious part of onboarding. In the GUI, you must click through multiple menus for every single user. With PowerShell, you can assign a license bundle to a list of users instantly.

Understanding License Assignments

To assign a license, you first need to identify the SkuId for the subscription you wish to assign. You can find these by running Get-MgSubscribedSku. Once you have the SkuId, you can use the Set-MgUserLicense command.

Practical Example: Assigning Licenses in Bulk

$SkuId = "your-sku-id-goes-here" # Replace with your actual SkuId
$Users = Import-Csv -Path "C:\Temp\users_to_license.csv"

foreach ($Row in $Users) {
    Set-MgUserLicense -UserId $Row.UserPrincipalName `
                      -AddLicenses @{SkuId = $SkuId} `
                      -RemoveLicenses @()
    
    Write-Host "License assigned to: $($Row.UserPrincipalName)" -ForegroundColor Cyan
}

Always keep a record of which users were assigned which licenses. If you ever need to perform a cleanup or a license audit, having a clean CSV export of your current user-to-license mapping is invaluable.


Not read yet

Managing Group Memberships at Scale

Adding users to groups is another area where bulk management shines. Whether you are adding new hires to a "Company-Wide" distribution list or assigning a group of users to a specific security group, the logic remains the same: identify the group, identify the users, and add them.

Adding Users to a Group

You will need the GroupId of the target group. You can find this by running Get-MgGroup -Filter "DisplayName eq 'YourGroupName'".

$GroupId = "your-group-id-here"
$Users = Import-Csv -Path "C:\Temp\group_members.csv"

foreach ($Row in $Users) {
    # Get the user ID first
    $User = Get-MgUser -UserId $Row.UserPrincipalName
    
    # Add the user to the group
    New-MgGroupMember -GroupId $GroupId -DirectoryObjectId $User.Id
    
    Write-Host "Added $($User.DisplayName) to group."
}

Warning: The Importance of Validation Never assume that the user exists before adding them to a group. Always perform a check (as shown in the code above) to verify that the user exists in the directory. If you attempt to add a non-existent user to a group, the script will throw an error and potentially stop the entire process.


Not read yet

Updating User Attributes (Bulk Modification)

Sometimes, you need to update an attribute for all users in a specific department. For example, if your company renames the "Sales" department to "Revenue," you need to update that property for every user currently assigned to "Sales."

The Update-MgUser Cmdlet

The Update-MgUser command is the standard way to modify existing attributes. You can filter users by their current attributes, loop through them, and update the value.

Practical Example: Updating Department Attributes

# Get all users in the Sales department
$Users = Get-MgUser -Filter "Department eq 'Sales'" -All

foreach ($User in $Users) {
    Update-MgUser -UserId $User.Id -Department "Revenue"
    Write-Host "Updated $($User.DisplayName) to Revenue department."
}

This is significantly faster than searching for each user individually in the admin center and manually editing their profile settings.


Not read yet

Best Practices for Bulk Management

Managing users in bulk requires discipline. A single poorly constructed script can cause widespread issues across your tenant. Follow these best practices to keep your environment safe.

1. Test in a Sandbox First

Never run a bulk script against your production environment without testing it on a small subset of users or, ideally, in a development tenant. Create a test CSV with three dummy users and verify that the script performs exactly as expected.

2. Use What-If Parameters

Many PowerShell cmdlets support the -WhatIf parameter. This parameter allows you to simulate the execution of a command without actually making any changes. It is a safety net that shows you exactly what the command would do if you ran it for real.

3. Log Your Actions

Always redirect the output of your scripts to a log file. If something goes wrong, you need a trail of what happened, when it happened, and which account was affected. You can use the Start-Transcript command at the beginning of your script to capture everything to a text file.

4. Handle Errors Gracefully

Use try-catch blocks in your scripts. This allows the script to handle errors—such as a user not being found or a permission issue—without crashing. You can log the error to a file and have the script continue to the next user in the list.

5. Document Your Scripts

Keep your scripts organized in a repository. Add comments that explain what each section of the code does. If you leave your role, the next administrator needs to be able to understand your automation logic without having to reverse-engineer it.


Not read yet

Common Pitfalls and How to Avoid Them

Even experienced administrators run into issues with bulk management. Being aware of these pitfalls can save you from significant downtime.

Pitfall 1: Rate Limiting

Microsoft 365 enforces rate limits on API calls. If you try to process 5,000 users in a single loop, the Microsoft Graph API may throttle your requests, causing the script to fail.

  • The Fix: Implement a small delay in your loop using Start-Sleep -Milliseconds 500. This keeps your request rate under the threshold while still maintaining high performance.

Pitfall 2: Incorrect CSV Encoding

Excel often saves CSVs in formats that can include hidden characters or strange encoding, leading to "User not found" errors even when the spelling looks correct.

  • The Fix: Always save your files as "CSV (Comma delimited) (*.csv)" and open them in a text editor like VS Code or Notepad++ to ensure they are clean and UTF-8 encoded.

Pitfall 3: Assuming User Objects Exist

As mentioned earlier, attempting to update or add a user that does not exist will break your script.

  • The Fix: Always verify the existence of the user object by retrieving it with Get-MgUser before performing further actions.

Pitfall 4: Forgetting the UsageLocation

A common error when creating users is forgetting the UsageLocation property. Without this, you cannot assign a license to the user.

  • The Fix: Always include the UsageLocation (e.g., "US", "GB", "CA") in your CSV template and ensure it is included in your New-MgUser command.

Not read yet

Comparison: Manual Management vs. Bulk PowerShell

Feature Manual Management (GUI) Bulk PowerShell
Speed Slow, linear Extremely fast
Accuracy Prone to human error High (scripted logic)
Scalability Poor High
Repetitiveness High fatigue Zero fatigue
Auditability Difficult to track Easy (via logs/scripts)
Learning Curve Low Moderate to High

Callout: The Philosophy of Infrastructure as Code Treat your user management scripts as "Infrastructure as Code." This means that your scripts should be version-controlled, documented, and tested just like software. When you treat your administrative tasks as code, you move from "fixing things" to "engineering solutions." This mindset change is the hallmark of a senior system administrator.


Step-by-Step Scenario: Onboarding 100 Employees

Let’s walk through a real-world scenario. You have been tasked with onboarding 100 new employees. You have been provided a CSV with their names, email addresses, and departments.

Step 1: Define the CSV Format

Ensure your CSV is named onboarding.csv and contains the columns: DisplayName, UserPrincipalName, Department, UsageLocation, Password.

Step 2: Write the Script

Write a script that creates the users, assigns them to their respective department groups (assuming the groups already exist), and assigns a license.

$Users = Import-Csv -Path "C:\Temp\onboarding.csv"
$SkuId = "your-license-sku-id"

foreach ($Row in $Users) {
    try {
        # Create the user
        $NewUser = New-MgUser -DisplayName $Row.DisplayName `
                             -UserPrincipalName $Row.UserPrincipalName `
                             -MailNickname ($Row.UserPrincipalName.Split('@')[0]) `
                             -UsageLocation $Row.UsageLocation `
                             -Department $Row.Department `
                             -AccountEnabled `
                             -PasswordProfile @{Password = $Row.Password; ForceChangePasswordNextSignIn = $true}
        
        # Assign license
        Set-MgUserLicense -UserId $NewUser.Id -AddLicenses @{SkuId = $SkuId} -RemoveLicenses @()
        
        # Add to department group
        $Group = Get-MgGroup -Filter "DisplayName eq '$($Row.Department)'"
        if ($Group) {
            New-MgGroupMember -GroupId $Group.Id -DirectoryObjectId $NewUser.Id
        }
        
        Write-Host "Successfully onboarded $($Row.DisplayName)" -ForegroundColor Green
    }
    catch {
        Write-Error "Failed to onboard $($Row.DisplayName). Error: $($_.Exception.Message)"
    }
}

Step 3: Run with -WhatIf (If supported) or Test Data

Before running on the full list, change the $Users import line to import a smaller file with only two users. Verify the output.

Step 4: Execute and Monitor

Once verified, run the script for the full list. Keep the PowerShell window open and watch the progress. If an error occurs, the catch block will alert you without stopping the script, allowing you to address the specific user later.


Not read yet

Frequently Asked Questions (FAQ)

Q: Do I need to be a developer to use PowerShell for user management? A: Not at all. You need to understand basic programming logic (loops, variables, if-statements), but the Microsoft Graph SDK does the heavy lifting. If you can follow a recipe, you can write these scripts.

Q: Is it dangerous to use these scripts? A: Any script has the potential to make mistakes if written incorrectly. This is why testing, the use of -WhatIf (where applicable), and proper error handling are non-negotiable.

Q: How do I handle users who have different licenses? A: You can add a LicenseType column to your CSV and use an if-else statement inside your loop to assign different SkuId values based on the user's role.

Q: What if I need to perform a task that isn't supported by the SDK? A: The Microsoft Graph API is vast. If a cmdlet doesn't exist, you can use the Invoke-MgGraphRequest command to send raw HTTP requests to the API. This gives you access to every single feature available in the platform.


Not read yet

Summary and Key Takeaways

Bulk user management is a critical skill for any modern Microsoft 365 administrator. By moving away from manual GUI-based management and toward scripted automation, you increase your efficiency, reduce the likelihood of configuration errors, and free up time for more strategic projects.

Key Takeaways for Your Toolkit:

  1. Automation is Essential: Manual processes do not scale. As your tenant grows, PowerShell becomes the only way to maintain consistency and speed.
  2. The CSV Workflow: Standardize your input data. A well-formatted CSV is the backbone of reliable bulk management.
  3. Safety First: Always test your scripts in a development environment or with a small sample size before deploying them to your entire user base.
  4. Error Handling: Use try-catch blocks to ensure your scripts are resilient. A single error should not bring your entire automation process to a halt.
  5. Audit and Log: Always document your changes. Use Start-Transcript or similar methods to keep a record of every action performed by your scripts.
  6. Principle of Least Privilege: Connect to your tenant using only the permissions required for the specific task at hand. Avoid using Global Admin credentials for routine user management.
  7. Continuous Learning: The Microsoft Graph API is constantly evolving. Stay updated with the latest documentation and module releases to ensure your scripts remain functional and efficient.

By applying these principles, you will transform from an administrator who struggles to keep up with the daily grind into an engineer who builds systems that work for you. Start small, build your library of reusable scripts, and keep refining your process. Your future self—and your organization—will thank you for the time and effort you invest in mastering these tools today.

Not read yet

Each section gets a ✓ as you scroll through it. Tap the button to jump to the next one.