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

A Proliferation of Guest User Accounts Within Tenants

Updated May 7, 2021

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.

All is good, except for the proliferation of guest accounts that can quickly accumulate inside a tenant. In short, a regular spring cleaning is needed to ensure that unwanted guests are ejected.

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 Stale Guest Users and their Group Membership

The script below does the following:

  • Finds all guest accounts in the tenant.
  • Checks each guest to discover its age based on the RefreshTokensValidFromDateTime attribute, which is updated when the guest account is created. The New-TimeSpan cmdlet calculates how many days have elapsed since Azure B2B Collaboration created the guest account in the tenant directory.
  • If the guest account is older than 365 days, we look for its group membership by running the Get-Recipient cmdlet to check the account’s distinguished name (an old but still useful X.500 construct) against the membership of Microsoft 365 groups. If you want to check guest accounts older or younger than 365 days, update the $GuestAccountAge variable with the number of days to check for.
  • 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, writes the contents of the array 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. 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. You need to connect your PowerShell session to Exchange Online and Azure Active Directory before running the script.

# Script to find Guest User Accounts in an Office 365 Tenant that are older than 365 days and the groups they belong to
# Find guest accounts
$GuestAccountAge = 365 # Value used for guest age comparison. If you want this to be a different value (like 30 days), change this here.
$GuestUsers = Get-AzureADUser -All $true -Filter "UserType eq 'Guest'" | Sort DisplayName
$Today = (Get-Date); $StaleGuests = 0
$Report = [System.Collections.Generic.List[Object]]::new()
# Check each account and find those over 365 days old
ForEach ($Guest in $GuestUsers) {
   $AADAccountAge = ($Guest.RefreshTokensValidFromDateTime | New-TimeSpan).Days
   If ($AADAccountAge -gt $GuestAccountAge) {
      Write-Host "Processing" $Guest.DisplayName
      $i = 0; $GroupNames = $Null
      # Find what Microsoft 365 Groups the guest belongs to... if any
      $DN = (Get-Recipient -Identity $Guest.UserPrincipalName).DistinguishedName 
      $GuestGroups = (Get-Recipient -Filter "Members -eq '$Dn'" -RecipientTypeDetails GroupMailbox | Select DisplayName, ExternalDirectoryObjectId)
      If ($GuestGroups -ne $Null) {
         ForEach ($G in $GuestGroups) { 
           If ($i -eq 0) { $GroupNames = $G.DisplayName; $i++ }
           {$GroupNames = $GroupNames + "; " + $G.DisplayName }
      $ReportLine = [PSCustomObject]@{
           UPN     = $Guest.UserPrincipalName
           Name    = $Guest.DisplayName
           Age     = $AADAccountAge
           Created = $Guest.RefreshTokensValidFromDateTime  
           Groups  = $GroupNames
           DN      = $DN}      
     $Report.Add($ReportLine) }
$Report | Sort Name | Export-CSV -NoTypeInformation c:\Temp\OldGuestAccounts.csv

Dealing with Special Characters in Guest Distinguished Names

A user reported that they had problems processing some guest accounts with the original version of the script. The issue was that the distinguished name of the guest accounts included an apostrophe like this:

CN=o’,OU=Microsoft Exchange Hosted Organizations,DC=EURPR04A002,DC=prod,DC=outlook,DC=com

Server-side filtering with Exchange Online PowerShell is picky when it comes to processing special characters like the apostrophe. Vasil Michev, the Technical editor for the Office 365 for IT Pros eBook, covers this point on his blog, so the solution was to add some code to check if the distinguished name contained an apostrophe and process it appropriately if true.

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.

25 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.

Leave a Reply

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