Using PowerShell to get Audit data for external users

Using PowerShell to get Audit data for external users header image

Allowing your users to share content in Office 365 through the use of external sharing is a powerful way to get things done. Inviting someone to collaborate or view documents you store on your team site is becoming easier and easier. As there is coming more and more control over external sharing options I recently found myself having to see what happens with external sharing requests. When the out of the box features are not enough you can expect PNP to solve some of the pain for you.

External Sharing Expiration Service

The External Sharing Expiration Service sample is a great way to have some control over your external users and let them expire after a specified amount of time. It is a great solution if you are concerned about all those external users who ever got invited and never have been removed. If you however want to get some feeling with your external users first, you can quite easily retrieve all the external users through PowerShell.

$extUsers = Get-MsolUser | Where-Object {$_.UserPrincipalName -like "*#EXT#*" }

With this information you can also ‘read’ the audit log from the security and compliance center in Office 365. It does require to be turned on but it will monitor any user activity in SharePoint Online and OneDrive for Business . Checkout the Office Support site to get an overview of all monitored activities. Any external user that does log in will thus end up in these logs. If you browse to it through the Security & Compliance Center you will be asked to start recording user and admin activity. As you would expect it is fairly easy to query these logs with PowerShell. You can use the Search-UnifiedAuditLog command.

A quick example to retrieve all external users and then retrieve their audit log events for the past 7 days would as easy as it sounds

$cred = Get-Credential

$session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $cred -Authentication Basic -AllowRedirection
Import-PSSession $session
Connect-MsolService -Credential $cred

$extUsers = Get-MsolUser | Where-Object {$_.UserPrincipalName -like "*#EXT#*" }

$extUsers | ForEach {
    $auditEventsForUser = Search-UnifiedAuditLog -EndDate $((Get-Date)) -StartDate $((Get-Date).AddDays(-7)) -UserIds $_.UserPrincipalName

    Write-Host "Events for" $_.DisplayName "created at" $_.WhenCreated

    $auditEventsForUser | FT
}

Remove-PSSession $session

Based on this script you will be presented with all the audit events present for external users. You could extend this to filter on RecordType or extrapolate the AuditData json object that contains more information about the event.

Loading comments…