Retrieve last sign-in time of all guest users via PowerShell?

5.3k Views Asked by At

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:

https://learn.microsoft.com/en-us/answers/questions/231133/azure-guest-user-account-last-signin-details.html

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??

1

There are 1 best solutions below

1
On BEST ANSWER

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:

image

After running the above script, csv file generated like below:

enter image description here