As Microsoft 365 administrators, it’s crucial to monitor and audit who has been invited into your tenant—especially guest users. In this article, we’ll walk through a Graph PowerShell script that retrieves audit logs specifically for guest invitations and displays the relevant details. This script leverages Microsoft Graph Directory Audit logs under the UserManagement category.
# Connect to Microsoft Graph with necessary scopes
Connect-MgGraph -Scopes "AuditLog.Read.All", "User.Read.All", "Directory.Read.All"
# Set time range (last 28 days, as per standard audit log retention)
$startDateTime = (Get-Date).AddDays(-28).ToString("yyyy-MM-ddTHH:mm:ssZ")
$endDateTime = (Get-Date).ToString("yyyy-MM-ddTHH:mm:ssZ")
# Fetch 'Invite external user' audit logs from UserManagement category
$logs = Get-MgAuditLogDirectoryAudit -Filter "category eq 'UserManagement' and activityDisplayName eq 'Invite external user' and activityDateTime ge $startDateTime and activityDateTime le $endDateTime" -All
# Prepare output array
$results = @()
foreach ($log in $logs) {
foreach ($target in $log.TargetResources) {
# Check if the target is a guest user
if ($target.UserPrincipalName -like "*#EXT#*" -or $target.UserPrincipalName -like "*@*") {
$results += [PSCustomObject]@{
"Display Name" = $target.DisplayName
"UPN" = $target.UserPrincipalName
"Sign In Status" = "Invited"
"Created Date/Time"= $log.ActivityDateTime
}
}
}
}
# Output in table format
$results | Format-Table -AutoSize
To make this script more robust or tailored to your organization’s needs, consider:
$results | Export-Csv -Path "GuestUserInvitations_AuditReport.csv" -NoTypeInformation -Encoding UTF8
Use Get-MgAuditLogSignIn to check if invited guests actually signed in:
Get-MgAuditLogSignIn -Filter "userPrincipalName eq 'guestuser@example.com'"
Build logic to compare invite date with actual sign-in to flag unused guest accounts.
Error | Cause | Solution |
Get-MgAuditLogDirectoryAudit : Access is denied. | Insufficient permissions | Use Connect-MgGraph -Scopes "AuditLog.Read.All" and ensure the account has AuditLog Reader role. |
The term 'and' is not recognized... | Prompt text or extra characters mistakenly copied into PowerShell | Only paste the code, not the instruction text or headers. |
UserPrincipalName is null | Some guest entries might not have UPN | Add a condition to skip entries with null UPNs. |
This Graph PowerShell script provides a simple yet powerful audit mechanism for tracking guest user invitations into your Microsoft 365 environment. With minor tweaks, it can serve as a foundation for more advanced reporting, automation, and compliance workflows. Whether you're a solo admin or part of a security team, auditing external access should always be a part of your routine—and this script gets you there quickly.
© m365corner.com. All Rights Reserved. Design by HTML Codex