Entra / Microsoft 365 · Users & guests
Last logon by external users
Find the last time guest accounts (external users) signed in to the Microsoft 365 tenant.
Connect & set up
Run these once per session. All scopes are read-only unless the script makes changes.
# Review required modules and connection steps before running.# Connect to Microsoft Graph or Exchange Online as needed for this script.
Run it
The main script. Copy it, or download the .ps1 and run it from your console.
param([int] $LookbackDays = 90,[string] $StartDate = (Get-Date).AddDays(-$LookbackDays),[string] $EndDate = (Get-Date).AddDays(+1))$Guests = (Get-AzureADUser -Filter "UserType eq 'Guest'" -All $True| Select Displayname, Mail, RefreshTokensValidFromDateTime | Sort RefreshTokensValidFromDateTime)Write-Host $Guests.Count "guest accounts found. Checking last connections..."$StartDate2 = (Get-Date).AddDays(-$LookbackDays)$Active = 0$EmailActive = 0$Inactive = 0$TeamsSpo = 0ForEach ($G in $Guests) {Write-Host "Checking" $G.DisplayName$Recs = $Null$UserId = $G.Mail# Handle account whose guest invitation is not redeemedIf ($Userid -eq $Null) {$UserId = "NullString"}$Recs = (Search-UnifiedAuditLog -UserIds $UserId -Operations UserLoggedIn, TeamsSessionStarted -StartDate $StartDate -EndDate $EndDate)If ($Recs -eq $Null) {Write-Host "No connections found in the last 90 days for" $G.DisplayName "created on" $G.RefreshTokensValidFromDateTime -Foregroundcolor Red# Check email tracking logs because guests might receive email from Groups. Account must be fully formed for the check. We can only go back 10 daysIf ($UserId -ne "NullString") {$EmailRecs = (Get-MessageTrace –StartDate $StartDate2 –EndDate $EndDate -Recipient $G.Mail)If ($EmailRecs.Count -gt 0) {Write-Host "Email traffic found for " $G.DisplayName "at" $EmailRecs[0].Received -foregroundcolor Yellow$Active++$EmailActive++ }}}Elseif ($Recs[0].CreationDate -ne $Null) {Write-Host "Last connection for" $G.DisplayName "on" $Recs[0].CreationDate "as" $Recs[0].Operations -Foregroundcolor Green$Active++$TeamsSpo++ }}Write-Host ""Write-Host "Statistics"Write-Host "----------"Write-Host "Guest Accounts " $Guests.CountWrite-Host "Active Guests " $ActiveWrite-Host "Active on Teams and SPO " $TeamsSPOWrite-Host "Active on Email " $EmailActiveWrite-Host "InActive Guests " ($Guests.Count - $Active)
Parameters
ParameterDefaultNotes
-LookbackDays90Number of days of sign-in history to review for guest accounts.-StartDate(Get-Date).AddDays(-90)Start of the reporting window.-EndDate(Get-Date).AddDays(+1)End of the reporting window.Attribution
Author
Office365itpros