Fetch Disabled Guest Users Created in Last 30 Days Using Graph PowerShell

Guest accounts are frequently created in Microsoft 365 environments for external collaboration. However, some guest accounts may be disabled shortly after creation due to:

  • Project cancellation
  • Security review
  • Access revocation
  • Duplicate invitations
  • Governance cleanup

In this article, we will retrieve: Guest users that were created in the last 30 days and are currently disabled. This report helps administrators quickly identify newly created guest accounts that are no longer active.

πŸš€ Community Edition Released!

Try the M365Corner Microsoft 365 Reporting Tool β€” your DIY pack with 20+ out-of-the-box M365 reports for Users, Groups, and Teams.

Script: Disabled Guest Users Created in Last 30 Days

# ==========================================
# Script: Disabled Guest Users Created in Last 30 Days
# ==========================================

# Connect to Microsoft Graph
Connect-MgGraph -Scopes "User.Read.All"

# Define date range (Last 30 Days)
$StartDate = (Get-Date).AddDays(-30).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")

# Fetch disabled guest users created in last 30 days
$DisabledGuests = Get-MgUser `
    -Filter "userType eq 'Guest' and accountEnabled eq false and createdDateTime ge $StartDate" `
    -ConsistencyLevel eventual `
    -CountVariable Count `
    -All `
    -Select "id,displayName,userPrincipalName,mail,createdDateTime,accountEnabled"

if ($DisabledGuests.Count -gt 0) {

    Write-Host "Disabled Guest Users Created in Last 30 Days: $Count" -ForegroundColor Green
    Write-Host "------------------------------------------------------"

    $Result = $DisabledGuests | Select-Object `
        DisplayName,
        UserPrincipalName,
        Mail,
        CreatedDateTime,
        AccountEnabled,
        Id

    # Display in console
    $Result | Format-Table -AutoSize

    # Export to CSV
    $ExportPath = ".\DisabledGuestUsers_CreatedLast30Days.csv"
    $Result | Export-Csv -Path $ExportPath -NoTypeInformation -Encoding UTF8

    Write-Host ""
    Write-Host "Results exported to: $ExportPath" -ForegroundColor Cyan
}
else {
    Write-Host "No disabled guest users were created in the last 30 days." -ForegroundColor Yellow
}
                            

How the Script Works

Let’s break down the key components.

  1. Connecting to Microsoft Graph
  2. Connect-MgGraph -Scopes "User.Read.All"

    This scope allows reading user properties across the tenant.

    Admin consent may be required.

  3. Calculating the Last 30 Days
  4. $StartDate = (Get-Date).AddDays(-30).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ")

    Microsoft Graph requires date filters in:

    • UTC
    • ISO 8601 format

    This ensures the filter works correctly with createdDateTime.

  5. Filtering Logic Explained
  6. -Filter "userType eq 'Guest' and accountEnabled eq false and createdDateTime ge $StartDate"

    This filter retrieves:

    • userType eq 'Guest' β†’ Only external B2B users
    • accountEnabled eq false β†’ Currently disabled accounts
    • createdDateTime ge β†’ Created within the last 30 days

    This is a current state report, not a historical disable report.

  7. Why -ConsistencyLevel Eventual is Required
  8. Advanced filters using:

    • Multiple conditions
    • $count
    • Complex queries

    Require: -ConsistencyLevel eventual. Without it, you may receive query errors.

  9. Selecting Required Properties
  10. We use:

    -Select "id,displayName,userPrincipalName,mail,createdDateTime,accountEnabled"

    Graph does not always return all properties by default. Explicit selection ensures:

    • CreatedDateTime is populated
    • AccountEnabled is returned correctly
  11. Exporting to CSV
  12. The script exports results to:

    DisabledGuestUsers_CreatedLast30Days.csv

    This makes it easy to:

    • Share with compliance teams
    • Archive for governance review
    • Perform further analysis

Further Enhancements

This script can be extended in several ways.

  1. Make Day Range Dynamic
  2. Instead of fixed 30 days:

    $Days = Read-Host "Enter number of days"
  3. Include ExternalUserState
  4. You can add:
    externalUserState
    To determine whether the guest has accepted the invitation.

  5. Identify Who Invited the Guest
  6. Pull invitation details from audit logs for deeper tracking.

  7. Automate Monthly Review
  8. Schedule this script to run:

    • Weekly
    • Monthly
    • Before compliance audits

Possible Errors and Solutions

Error Cause Solution
Insufficient privileges to complete the operation Missing Graph permissions. Connect-MgGraph -Scopes "User.Read.All"
Ensure admin consent is granted.
CreatedDateTime or AccountEnabled is blank Properties not explicitly selected. Always use:
-Select "createdDateTime,accountEnabled"
Request_UnsupportedQuery Missing consistency header. Add:
-ConsistencyLevel eventual
No results returned No guest users meet all three conditions:
  • Guest
  • Disabled
  • Created in last 30 days
This may be normal depending on tenant activity.

Conclusion

Monitoring disabled guest accounts is an important governance task in Microsoft 365.

This script provides administrators with a quick and effective way to:

  • Identify recently created guest accounts that are now disabled
  • Detect onboarding issues
  • Validate short-term external access
  • Strengthen tenant security posture

For tenants with heavy external collaboration, incorporating this script into a periodic review process is highly recommended.

Graph PowerShell Explorer Widget

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


Permission Required

Example:


                            


                            


                            

© Created and Maintained by LEARNIT WELL SOLUTIONS. All Rights Reserved.