I am trying to export a list of guest user's last sign-in time to a CSV file via PowerShell.
Atfirst, I used Connect-AzureAD
to get into Azure AD from PowerShell.
I found the below command where I can fetch only the guest users list.
Get-AzureADUser -Filter "UserType eq 'Guest' and AccountEnabled eq true"
Now, from the above list, I want to retrieve the last sign-in time property along with their displayname or UPN.
I found below link that is partially similar my scenario:
In the above link, they are checking whether the guest user has logged in for the last 30 days or not. But, I want to retrieve the last signInTime of all guest users.
Is this possible? Has anyone tried something like this and achieved it??
I tried in my environment and got last sign-in time of all guest users successfully by using the below PowerShell Script:
$guests = Get-AzureADUser -Filter "userType eq 'Guest'" -All $true
foreach ($guest in $guests) {
$Userlogs = Get-AzureADAuditSignInLogs -Filter "userprincipalname eq `'$($guest.mail)'" -ALL:$true
if ($Userlogs -is [array]) {
$timestamp = $Userlogs[0].createddatetime
}
else {
$timestamp = $Userlogs.createddatetime
}
$Info = [PSCustomObject]@{
Name = $guest.DisplayName
UserType = $guest.UserType
LastSignin = $timestamp
}
$Info | Export-csv C:\GuestUserLastSignins.csv -NoTypeInformation -Append
Remove-Variable Info
}
Write-Host -ForegroundColor Green "Exported Logs successfully"
Output:
After running the above script, csv file generated like below: