Last active
December 2, 2021 19:51
-
-
Save MatthewJDavis/f46fe88a4d61fd451f7b814d3e4f2301 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <# | |
| .DESCRIPTION | |
| Get last login of Guest user in Azure AD | |
| Adapted from https://cloudtech.nu/2020/05/03/export-azure-ad-last-logon-with-powershell-graph-api/#comments | |
| .NOTES | |
| Requries an Azure App registered with Add AuditLog.Read.All, Directory.Read.All, User.Read.All permissions. | |
| Set clientID, tenantName, clientSecret in $env: vars. | |
| #> | |
| $clientID = $env:clientID | |
| $tenantName = $env:tenantName | |
| $clientSecret = $env:clientSecret | |
| $ReqTokenBody = @{ | |
| Grant_Type = "client_credentials" | |
| Scope = "https://graph.microsoft.com/.default" | |
| client_Id = $env:clientID | |
| Client_Secret = $env:clientSecret | |
| } | |
| $TokenResponse = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$TenantName/oauth2/v2.0/token" -Method POST -Body $ReqTokenBody | |
| $uri = 'https://graph.microsoft.com/beta/users?$filter=UserType eq ''Guest''&$select=displayName,userPrincipalName,signInActivity' | |
| $data = while (-not [string]::IsNullOrEmpty($uri)) { | |
| $apiCall = try { | |
| Invoke-RestMethod -Headers @{Authorization = "Bearer $($Tokenresponse.access_token)" } -Uri $uri -Method Get | |
| } | |
| catch { | |
| $_.ErrorDetails.Message | ConvertFrom-Json | |
| } | |
| $uri = $null | |
| if ($apiCall) { | |
| $uri = $apiCall.'@odata.nextLink' | |
| $apiCall | |
| } | |
| } | |
| $result = ($data | select-object Value).Value | |
| $result | Select-Object DisplayName, UserPrincipalName, @{n = "LastLoginDate"; e = { $_.signInActivity.lastSignInDateTime } } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment