🔧 New: User Management Graph PowerShell Toolkit

Simplify user tasks like bulk creation, updates, password resets, deletions, license checks & more — all from one place.

🚀 Launch Toolkit

Fetch and Mail Microsoft 365 Users from Specific Department Using PowerShell

Managing departmental user lists manually can be tedious. With Microsoft Graph PowerShell, you can automate the entire process — from fetching the list of users belonging to a specific department to emailing that list directly to an administrator.

Below is a simple, no-functions script that gets the job done.


i) Script


    # ===== Simple Graph PowerShell Script =====
    # Fetch all users from a specific department and email the list to admin
    # Requires: Microsoft.Graph module
    # Scopes: User.Read.All, Mail.Send

    # --- Variables ---
    $Department = "Marketing"
    $FromUser   = "admin@contoso.com"   # Sender (must have mailbox)
    $To         = "it-ops@contoso.com"  # Recipient
    $Subject    = "User list for department"
    $CsvOutDir  = "$env:TEMP"

    # --- Connect to Microsoft Graph ---
    Import-Module Microsoft.Graph -ErrorAction Stop
    Connect-MgGraph -Scopes "User.Read.All","Mail.Send"

    # --- Build Filter (escape single quotes in department) ---
    $DepartmentEscaped = $Department.Replace("'", "''")
    $filter = "department eq '$DepartmentEscaped' and userType eq 'Member' and accountEnabled eq true"

    # --- Fetch Users ---
    $selectProps = "id","displayName","userPrincipalName","jobTitle","department","accountEnabled"
    $users = Get-MgUser -All -Filter $filter -ConsistencyLevel eventual -Property $selectProps |
    Select-Object $selectProps

    # --- Export to CSV ---
    if (-not (Test-Path -Path $CsvOutDir)) { New-Item -ItemType Directory -Path $CsvOutDir | Out-Null }
    $ts = Get-Date -Format "yyyyMMdd_HHmmss"
    $csvPath = Join-Path $CsvOutDir ("Users_{0}_{1}.csv" -f ($Department -replace '\s+','_'), $ts)
    $users | Export-Csv -Path $csvPath -NoTypeInformation -Encoding UTF8

    # --- Prepare HTML Body ---
    $summaryHtml = @"
    <html>
    <body style='font-family:Segoe UI,Arial,sans-serif'>
        <h3>Department User Lis</h3>
        <p>Department: <b>$Department</b></p>
        <p>Total users: <b>$($users.Count)</b></p>
        <p>The full list is attached as a CSV.</p>
    </body>
    </html>
    "@

    # --- Prepare Attachment ---
    $fileBytes     = [System.IO.File]::ReadAllBytes($csvPath)
    $base64Content = [System.Convert]::ToBase64String($fileBytes)
    $csvFileName   = [System.IO.Path]::GetFileName($csvPath)
    $attachment = @{
        "@odata.type" = "#microsoft.graph.fileAttachment"
        name          = $csvFileName
        contentBytes  = $base64Content
        contentType   = "text/csv"
    }

    # --- Prepare Mail Object (use ${Subject} to avoid the colon parsing issue) ---
    $mail = @{
    message = @{
        subject = "${Subject}: $Department"
        body    = @{
            contentType = "HTML"
            content     = $summaryHtml
        }
    toRecipients = @(@{ emailAddress = @{ address = $To } })
    attachments  = @($attachment)
    }
    saveToSentItems = $true
    }

    # --- Send Email ---
    Send-MgUserMail -UserId $FromUser -BodyParameter $mail
    Write-Host "Done. CSV saved at: $csvPath" -ForegroundColor Green


ii) How the Script Works

  1. Variable Setup
  2. The script starts with user-defined variables for the department name, sender and recipient email addresses, subject line, and output directory for the CSV file.

  3. Graph Connection
  4. It loads the Microsoft Graph PowerShell module and connects to Microsoft Graph with delegated scopes User.Read.All (to read user details) and Mail.Send (to send emails).

  5. Filtering Users
  6. An OData filter is constructed to fetch only enabled members from the specified department.

  7. Data Retrieval
  8. Get-MgUser retrieves the user list, selecting only the required properties such as DisplayName, UserPrincipalName, and JobTitle.

  9. Exporting to CSV
  10. The script creates a CSV file containing the filtered user data in the specified directory.

  11. Email Preparation
  12. An HTML body summarizing the department name and total count is created, and the CSV is read into a Base64-encoded attachment.

  13. Sending the Email
  14. Using Send-MgUserMail, the message with the attachment is sent from the specified sender account to the admin recipient.


iii) Further Enhancements

  • Prompt for Variables: Make the script interactive by prompting for department and email addresses at runtime.
  • Multiple Department Support: Allow the script to handle multiple departments in a single run.
  • App-Only Authentication: Replace delegated authentication with certificate-based app authentication for automation scenarios without user sign-in.
  • Error Logging: Implement logging to capture API errors or delivery failures.
  • CSV Inline Preview: Include a preview of the first 10 users in the email body.

Possible Errors & Solutions

Error Cause Solution
Authorization_RequestDenied Missing permissions for User.Read.All or Mail.Send Ensure the account grants consent for required delegated permissions.
Module not found Microsoft.Graph module is not installed Run Install-Module Microsoft.Graph -Scope CurrentUser before running the script.
InvalidVariableReferenceWithDrive on subject line Colon used after $Subject variable without braces Use "${Subject}: $Department" as shown in the script.
Empty CSV output No users match the filter Verify that the department name matches exactly in Azure AD.
Mail not sent FromUser mailbox doesn’t exist or lacks send rights Use a mailbox-enabled account and ensure it can send emails.

Conclusion

This script streamlines the process of generating and distributing departmental user lists by combining user retrieval and email delivery in one workflow. It’s straightforward, requires minimal configuration, and can be adapted for more advanced automation scenarios.

By leveraging Microsoft Graph PowerShell, admins can eliminate repetitive manual exports, ensuring faster, more accurate reporting and improved operational efficiency.


Graph PowerShell Explorer Widget

20 Graph PowerShell cmdlets with easily accessible "working" examples.


Permission Required

Example:


                


                


                

© m365corner.com. All Rights Reserved. Design by HTML Codex