Simplify user tasks like bulk creation, updates, password resets, deletions, license checks & more — all from one place.
🚀 Launch ToolkitManaging 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.
# ===== 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
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.
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).
An OData filter is constructed to fetch only enabled members from the specified department.
Get-MgUser retrieves the user list, selecting only the required properties such as DisplayName, UserPrincipalName, and JobTitle.
The script creates a CSV file containing the filtered user data in the specified directory.
An HTML body summarizing the department name and total count is created, and the CSV is read into a Base64-encoded attachment.
Using Send-MgUserMail, the message with the attachment is sent from the specified sender account to the admin recipient.
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. |
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.
© m365corner.com. All Rights Reserved. Design by HTML Codex