How to Report Old Guest Accounts and Their Membership of Microsoft 365 Groups (and Teams)

A Proliferation of Guest User Accounts Within Tenants

Updated July 19. 2023

Azure Active Directory Guest User Accounts are terrifically useful in terms of allowing people outside your Microsoft 365 tenant to access resources inside the tenant. Applications like Teams, SharePoint Online, Planner, and Outlook Groups use the Azure B2B Collaboration framework to create new guest accounts to share information, whether it’s the membership of a team or access to a shared document or folder.

Guest accounts might be needed for to share just one document. Old guest accounts can accumulate over time. A regular spring cleaning is needed to ensure that you detect old guest accounts that are possibly no longer needed.

The Problem of Deciding When to Leave

As always, the problem is to decide when a guest account should be removed. Left by themselves, guest accounts will remain in the tenant directory because neither Office 365 nor Azure Active Directory include an automated method to clean up guests past their best-by date. One approach is to review guest accounts that are older than a certain age and look for evidence to indicate if they should be removed.

For example, you might decide that membership of multiple Microsoft 365 groups (aka Office 365 groups) is sufficient reason to keep guest accounts. The logic here is that these memberships give people access to Teams (conversations), Outlook Groups (conversations delivered via email), and Planner (group tasks). Therefore, if we write a script to scan for guest accounts older than x days and then check if these accounts are members of groups, we should have some evidence upon which to base a decision to remove or keep.

PowerShell Script to Highlight Old Guest Accounts and their Group Membership

The script below does the following:

  • Connects to the Graph with the Connect-MgGraph cmdlet.
  • Finds all guest accounts in the tenant using the Get-MgUser cmdlet.
  • Checks each guest to discover its age using the account creation date.
  • If the guest account is older than 365 days, we look for its group membership by running the Get-MgUserMemberOf cmdlet and report the display names of any groups found.
  • Checks the last sign-in activity for the account. This could be an important indicator that the account is active.
  • Writes the discovered information out to an array.
  • After all guest accounts are processed, the script writes the contents of the array containing information about old guest accounts to a CSV file.

Some example code is shown below. The latest version of the script is available on GitHub and is the version which you should download and use. The latest version runs with the Microsoft Graph PowerShell V2 cmdlets.

Remember that you might want to update the code to add error handling and do whatever testing is necessary before running the script against your production tenant.

# Script to find Old Guest Accounts in an Office 365 Tenant that are older than 365 days and the groups they belong to
# Find guest accounts

Write-Host "Finding Guest Accounts..."
[Array]$GuestUsers = Get-MgUser -Filter "userType eq 'Guest'" -All -Property Id, displayName, userPrincipalName, createdDateTime, signInActivity `
    | Sort-Object displayName
$i = 0; $Report = [System.Collections.Generic.List[Object]]::new()
# Loop through the guest accounts looking for old accounts 
ForEach ($Guest in $GuestUsers) {
# Check the age of the guest account, and if it's over the threshold for days, report it
   $AccountAge = ($Guest.CreatedDateTime | New-TimeSpan).Days
   If ($AccountAge -gt $AgeThreshold) {
      $ProgressBar = "Processing Guest " + $Guest.DisplayName + " " + $AccountAge + " days old " +  " (" + $i + " of " + $GuestUsers.Count + ")"
      Write-Progress -Activity "Checking Guest Account Information" -Status $ProgressBar -PercentComplete ($i/$GuestUsers.Count*100)
      $GroupNames = $Null
      # Find what Microsoft 365 Groups the guest belongs to... if any
     [array]$GuestGroups = (Get-MgUserMemberOf -UserId $Guest.Id).additionalProperties.displayName
     If ($GuestGroups) {
        $GroupNames = $GuestGroups -Join ", " 
     } Else {
        $GroupNames = "None"
#    Find the last sign-in date for the guest account, which might indicate how active the account is
     $UserLastLogonDate = $Null
     $UserLastLogonDate = $Guest.SignInActivity.LastSignInDateTime
     If ($Null -ne $UserLastLogonDate) {
        $UserLastLogonDate = Get-Date ($UserLastLogonDate) -format g
     } Else {
        $UserLastLogonDate = "No recent sign in records found" 

     $ReportLine = [PSCustomObject][Ordered]@{
           UPN               = $Guest.UserPrincipalName
           Name              = $Guest.DisplayName
           Age               = $AccountAge
           "Account created" = $Guest.createdDateTime 
           "Last sign in"    = $UserLastLogonDate 
           Groups            = $GroupNames }     
     $Report.Add($ReportLine) }
} # End Foreach Guest

Sample Report File

The output CSV file is shown (somewhat obscured to protect the names of the guilty) in Figure 1. Any guest that isn’t a member of at least one Microsoft 365 group is a potential delete target. As you can see from the created column, it’s easy for old and stale guest accounts to linger on unless you clean them up from time to time.

 Reporting old guest user accounts and their group membership
Figure 1: Reporting old guest user accounts and their group membership

Details of a more comprehensive report of membership of Microsoft 365 Groups including both tenant and guest members and summary details are explained in this article.

We have lots of other PowerShell examples of how to manage Azure Active Directory guest users and other Office 365 objects in the Office 365 for IT Pros eBook.

30 Replies to “How to Report Old Guest Accounts and Their Membership of Microsoft 365 Groups (and Teams)”

    1. Access reviews are indeed a good way to push responsibility down to group owners. However, they require Azure AD Premium licenses and don’t give tenants an overview of what’s happening with guests across all groups.

  1. I must be missing some simple step. Powershell is dumping this error message for each user found. Can someone help?

    Get-Recipient : The term ‘Get-Recipient’ is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included,
    verify that the path is correct and try again.
    At line:13 char:14
    + $DN = (Get-Recipient -Identity $Guest.UserPrincipalName).Distin …
    + ~~~~~~~~~~~~~
    + CategoryInfo : ObjectNotFound: (Get-Recipient:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

    1. PowerShell is telling you that it can’t find the Get-Recipient cmdlet. This is most likely because you haven’t connected to Exchange Online.

  2. Has the RefreshTokensValidFromDateTime always been the creation date I have the feeling that this changed? I was also interested to see that there is a creation date in the ExtensionProperty (Get-AzureADUser -ObjectId Might be in the previewonly would need to check. The onPremisesDistinguishedName is also great add we can do alot with this value in a multi forest environment.

    1. For guest accounts, I think the two values will be the same, but if you want to use createdDateTime in the script replace the line with:

      $AADAccountAge = ((Get-AzureADUser -ObjectId $Guest.UserPrincipalName).ExtensionProperty.createdDateTime | New-TimeSpan).Days

      1. Thanks Tony. I took inspiration from your blog post and script and created a end to end work flow based on the new signin logs data in Graph. I have found that this has broader scope, faster and more reliable than Search-UnifiedAuditLog. I gave you a little credit in the script as you started the conversation 🙂 I hope that’s ok? Let me know. JB

      2. Very cool! I love the way people take ideas and develop them in PowerShell…

      3. BTW, one thing that’s good about Search-UnifiedAuditLog is that it delivers real activity data. The sign in information is interesting, but a client can sign in and stay signed in and active for quite a while without their sign in date being updated (because they haven’t been forced to sign in again). So the sign in data is accurate but misleading as an indicator of activity.

      4. Where the session timeout is I’m not sure for the auditlogs is it 8 hours or 6 days ( Keep me signed in) it would be good to test and confirm the results. Sounds like a good topic for a new blog post 🙂

      5. Audit log data should be available within 15 minutes of a SharePoint or Exchange event. It can take longer for events from other workloads…

  3. This works a treat and I’ve now a report of several 100 guests and only two of them are members of groups. It could be the groups they used to be members of no longer exist. We’re not using guest access at the moment – as in inviting new guests to Groups/Teams. We disabled it for a lengthy period of time and during that time guests have been added to the directory… erm? Is this a quirk of Onedrive external sharing when used with ‘share with specific people’ and it adds them to the directory? Thanks for any pointers.

  4. Hi – Im running into an issue with the script, it seems to run fine until it hit a certain guest account which stops the script. Any thoughts on how to resolve? Thank you for sharing btw!

    Processing O’Malley, Matthew
    Processing O’Neal, Linda
    Cannot bind parameter ‘Filter’ to the target. Exception setting “Filter”: “Invalid filter syntax. For a description of
    the filter parameter syntax see the command help.
    “Members -eq ‘CN=linda.o’\#EXT\#,,OU=Microsoft Exchange Hosted
    Organizations,DC=NAMPRXXXXXX,DC=prod,DC=outlook,DC=com'” at position 25.”
    At C:\Users\xxxxx\AppData\Local\Temp\2\tmp_q5kd52cd.rox\tmp_q5kd52cd.rox.psm1:30612 char:9
    + $steppablePipeline.End()
    + ~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : WriteError: (:) [Get-Recipient], ParameterBindingException
    + FullyQualifiedErrorId : ParameterBindingFailed,Microsoft.Exchange.Management.RecipientTasks.GetRecipient

    1. I have posted a new version of the script to GitHub which processes guest accounts with apostrophes in their distinguished name. Please try that and let me know if you have any other problems.

  5. Is it possible to pull their last login time, maybe set it to filter for 365 as well. That way we know it’s truely stale and can be removed. We have projects that go for 3 years, I feel the last login time would be crucial for our scenario.

    1. Seeing that there’s nothing better to do on a Friday evening, I updated the script to add the check for the last Azure AD sign in activity. The updated script is available from GitHub.

      1. Hello Tony,

        Thanks for your great script but I did get a “too many requests” message on this command: Get-AzureADAuditSignInLogs.

  6. I also encountered the ‘too many requests’ but was able to workaround this by adding “Start-Sleep -Millseconds 500” at the end of the ForEach loop.

  7. I modified line 41 to include a couple of other attributes (Select DisplayName, ExternalDirectoryObjectId, ManagedBy, Notes, PrimarySmtpAddress). Curious if it’s possible to get the primary email or UPN of that ManagedBy attribute? I was thinking maybe an expression might work by calling on Get-Recipient again but not sure how to set that correctly.

    1. I believe ManagedBy is returned as an array. If my recollection is correct, you could go through the array and use Get-Recipient or Get-ExoMailbox to return whatever properties you want for each item.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.