Quick And Easy PowerShell Report For Azure AD Guest User Last Sign In

Microsoft has some cool tools for Guest user management. Implementing Access Reviews for example is great for ensuring expiration of Guest access when needed. We can also control who can invite Guests and which domains we allow Guests from. When this is all set up we have some really great governance over our B2B strategy in Microsoft 365. Unfortunately, there are a ton of organizations who didn’t have a full governance plan from day 1 and are now in remediation of Guest sprawl.

To help out with this remediation process, I’ve put together a straightforward script (available on GitHub) which will pull all guest users in a tenant, search the logs for the last sign in date/time and also list any apps they’ve logged into. This report is limited by the retention of AAD logs which is 30 days so keep that in mind when running. You’ll need to have an output folder present at c:\temp to export the results.

The only module required for this script is the AzureADPreview PowerShell Module which can be installed using the command “Install-Module AzureADPreview”

<#
    Author: Sean McAvinue
    Contact: Sean@seanmcavinue., Twitter: @Sean_McAvinue
    .SYNOPSIS
    Gets guest users last sign in action from AAD logs and exports user and signin list to CSV in C:\temp


#>
azureadpreview\Connect-azuread
##Get all guest users
$guests = Get-AzureADUser -Filter "userType eq 'Guest'" -All $true 

##Loop Guest Users
foreach ($guest in $guests) {

    ##Get logs filtered by current guest
    $logs = Get-AzureADAuditSignInLogs -Filter "userprincipalname eq `'$($guest.mail)'" -ALL:$true 

    ##Check if multiple entries and tidy results
    if ($logs -is [array]) {
        $timestamp = $logs[0].createddatetime
    }
    else {
        $timestamp = $logs.createddatetime
    }

    ##Build Output Object
    $object = [PSCustomObject]@{

        Userprincipalname = $guest.userprincipalname
        Mail              = $guest.mail
        LastSignin        = $timestamp
        AppsUsed          = (($logs.resourcedisplayname | select -Unique) -join (';'))
    }

    ##Export Results
    $object | export-csv C:\temp\GuestUserSignins.csv -NoTypeInformation -Append

    Remove-Variable object
}


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s