Microsoft Entra ID · PowerShell 7.6
Guest accounts with no sign-in in N days
Which guest (B2B) accounts have not signed in successfully for 90 days (or the number of days you pass), including guests who never signed in at all?
Script
#Requires -Modules Microsoft.Graph.Authentication, Microsoft.Graph.Users
# Guest accounts with no successful sign-in in the last -Days days (or never). Read-only.
param(
[int]$Days = 90
)
Connect-MgGraph -Scopes 'User.Read.All', 'AuditLog.Read.All' -NoWelcome
$cutoff = (Get-Date).AddDays(-$Days)
Get-MgUser -All -Filter "userType eq 'Guest'" -Property 'id', 'displayName', 'mail', 'userPrincipalName', 'createdDateTime', 'externalUserState', 'accountEnabled', 'signInActivity' |
Where-Object { $null -eq $_.CreatedDateTime -or $_.CreatedDateTime -lt $cutoff } |
ForEach-Object {
[pscustomobject]@{
DisplayName = $_.DisplayName
Mail = $_.Mail
InvitationState = $_.ExternalUserState
AccountEnabled = $_.AccountEnabled
CreatedDateTime = $_.CreatedDateTime
LastSuccessfulSignIn = $_.SignInActivity.LastSuccessfulSignInDateTime
UserPrincipalName = $_.UserPrincipalName
}
} |
Where-Object { $null -eq $_.LastSuccessfulSignIn -or $_.LastSuccessfulSignIn -lt $cutoff } |
Sort-Object LastSuccessfulSignIn
Checked automatically against Microsoft's published cmdlet reference. KBY hasn't run it in your tenant; run it in a test environment first.
Reading the output
- Uses signInActivity.lastSuccessfulSignInDateTime, the most recent successful interactive or non-interactive sign-in. Reading signInActivity needs a Microsoft Entra ID P1 or P2 licence and AuditLog.Read.All; without them the request fails or LastSuccessfulSignIn is empty for everyone.
- signInActivity isn't returned for a user who never signed in or last signed in before April 2020, so those guests show an empty LastSuccessfulSignIn.
- Guests created inside the window are left out, because they haven't had -Days to sign in yet. Guests with no createdDateTime (some accounts created before June 2018) are included.
- InvitationState is externalUserState: PendingAcceptance means the invitation was never redeemed.
- This only lists accounts. Microsoft's guidance for removing stale guests uses access reviews, so the guest's sponsor or the resource owner confirms first.
Sources
The Microsoft reference page for every cmdlet the script calls, plus the API and product pages behind each permission and caveat.
Connect-MgGraph (Microsoft.Graph.Authentication)Get-MgUser (Microsoft.Graph.Users)List users: permissions, and signInActivity licence and permission requirementssignInActivity resource type: lastSuccessfulSignInDateTimeuser resource type: userType, externalUserState, createdDateTimeHow to manage inactive user accounts in Microsoft Entra IDMonitor and clean up stale guest accounts using access reviewsGet-Date (Microsoft.PowerShell.Utility)Where-Object (Microsoft.PowerShell.Core)ForEach-Object (Microsoft.PowerShell.Core)Sort-Object (Microsoft.PowerShell.Utility)