Back to script library
Entra / Microsoft 365 · SharePoint & OneDrive

Find who created guests through SPO sharing

Find who created new guest accounts in a Microsoft 365 tenant through SharePoint Online sharing invitations.

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); $StartDate = (Get-Date).AddDays(-$LookbackDays); $NewGuests = 0
)
$Records = (Search-UnifiedAuditLog -StartDate $StartDate -EndDate $EndDate -Operations "SharingInvitationCreated" -ResultSize 2000 -Formatted)
If ($Records.Count -eq 0) {
Write-Host "No Sharing Invitations records found." }
Else {
Write-Host "Processing" $Records.Count "audit records..."
$Report = [System.Collections.Generic.List[Object]]::new()
ForEach ($Rec in $Records) {
$AuditData = ConvertFrom-Json $Rec.Auditdata
# Only process the additions of guest users to groups
If ($AuditData.TargetUserOrGroupName -Like "*#EXT#*") {
$TimeStamp = Get-Date $Rec.CreationDate -format g
# Try and find the timestamp when the invitation for the Guest user account was accepted from AAD object
Try {$AADCheck = (Get-Date(Get-AzureADUser -ObjectId $AuditData.TargetUserOrGroupName).RefreshTokensValidFromDateTime -format g) }
Catch {Write-Host "Azure Active Directory record for" $AuditData.UserId "no longer exists" }
If ($TimeStamp -eq $AADCheck) { # It's a new record, so let's write it out
$NewGuests++
$ReportLine = [PSCustomObject][Ordered]@{
TimeStamp = $TimeStamp
InvitingUser = $AuditData.UserId
Action = $AuditData.Operation
URL = $AuditData.ObjectId
Site = $AuditData.SiteUrl
Document = $AuditData.SourceFileName
Guest = $AuditData.TargetUserOrGroupName }
$Report.Add($ReportLine)}}
}}
$Report | Format-Table TimeStamp, Guest, Document -AutoSize

Parameters

ParameterDefaultNotes
-LookbackDays90Number of days to search for guest accounts created through sharing invitations.
-StartDate(Get-Date).AddDays(-90)Start of the audit log search window.
-EndDate(Get-Date).AddDays(1)End of the audit log search window.
Attribution