Track your invites | With the external sharing functionality in O365, Microsoft has provided companies with a powerful and easy way to collaborate with external partners. With new guest users added every day, one of my customers asked if it’s possible to track who invited who since they wanted to track this and have this data available when users are leaving the company to know which guests are invited by users no longer in the company.
In the audit log in Azure AD this can easily be accomplished by searching for the activity ”invite external users”. The longest date range you can select is one month.

However, this needs to be done manually, and to find out who invited who you need to open each entry making the process cumbersome. We want to do this using powershell instead to automate the process.
With the graph api, Microsoft has exposed this data, so it is easy to access it so that we can store it offline in a csv file or database etc and then make decisions on what to do with the information. In my use case, this is a key part since you only have data for the last month. So, we need to store this data somewhere so that it can be queried when a user leaves the company. In this blog post, I will only export it to a csv file, but you will get the general idea.
Let’s begin
We will use the graph API to retrieve this data, and to be able to do this we first need to create an application in Azure AD that we will give the necessary permissions to read the audit log data. Since there are a lot of information available that describes how this is done I will not add that content to this post. Instead, you can have a look at this post from my colleague Daniel:
Since the script will be running unattended we will need to use following application permissions.

Once the application is created in Azure AD, it needs to be consented by an administrator. In a text editor, create following URL string and add the values of the application id and redirect url:
https://login.microsoftonline.com/common/adminconsent?client_id=<Application ID>&state=12345&redirect_uri=<redirect url>
Then use the link to consent the application. Once the application is consented the following script can be used to access the data. Note that the beta endpoints are used to access the audit records in this example.
Download the script here!

The first function will be used to get the token for the application to extract the data. The second function is used to see last sign-in time of the guest.
We also have the GuestTracker class that is used to build an object to store the result before export.
The next part is where we get the actual token and query the audit log. You will need to add the applicationID, Secret and TenantID to this section.

Then we loop through the result and export each entry to a csv file.

An example output from the script:

That’s all for this time!
/Henrik