Get azure users signin using Microsoft graph api

A.Elrayes 186 Reputation points
2023-03-26T09:59:23.54+00:00

Hi Team,

I have a script to get users sign-ins using microsoft graph API.

The script was working for several months and suddenly stopped giving the below error:

Invoke-RestMethod : The remote server returned an error: (400) Bad Request.
At C:\Users\alaa.elrayes\Desktop\Get_O365_Inactive.ps1:43 char:14
+ ... Response =  Invoke-RestMethod -Method GET -Uri $ApiUrl -ContentType " ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

My script as the below:

$tenantID = "" #your tenantID or tenant root domain $appID = "" #the GUID of your app. $client_secret = "" #client secret for the app

#Prepare token request $url = 'https://login.microsoftonline.com/' + $tenantId + '/oauth2/v2.0/token'

$body = @{

grant_type = "client_credentials"
client_id = $appID
client_secret = $client_secret
scope = "https://graph.microsoft.com/.default"

}

#Obtain the token Write-Verbose "Authenticating..." try { $tokenRequest = Invoke-WebRequest -Method Post -Uri $url -ContentType "application/x-www-form-urlencoded" -Body $body -UseBasicParsing -ErrorAction Stop } catch { Write-Host "Unable to obtain access token, aborting..."; return }

$AccessToken = ($tokenRequest.Content | ConvertFrom-Json).access_token

$authHeader = @{ 'Content-Type'='application\json' 'Authorization'="Bearer $token" }

#Form request headers with the acquired $AccessToken $headers = @{'Content-Type'="application\json";'Authorization'="Bearer $AccessToken"}

#This request get users list with signInActivity. $ApiUrl = "https://graph.microsoft.com/beta/users?$select=displayName,userPrincipalName,signInActivity,userType,accountEnabled,userType,assignedLicenses&$top=999"

$Result = @() While ($ApiUrl -ne $Null) #Perform pagination if next page link (odata.nextlink) returned. { $Response = Invoke-RestMethod -Method GET -Uri $ApiUrl -ContentType "application\json" -Headers $headers if($Response.value) { $Users = $Response.value ForEach($User in $Users) {

if(($User.accountEnabled -eq $true)-and ($User.userType -contains "Member") -and ($User.displayName -notmatch "HealthMailbox") -and ($User.displayName -notmatch "CVEXBackupAccount") -and ($User.displayName -notmatch "manageengine") -and ($User.displayName -notmatch "On-Premises Directory")){

$Result += New-Object PSObject -property $([ordered]@{ "Display Name" = $User.displayName "Last Logon Time Stamp" = if($User.signInActivity.lastSignInDateTime) { [DateTime]$User.signInActivity.lastSignInDateTime } Else {$null} "Logon Name" = $User.userPrincipalName IsLicensed = if ($User.assignedLicenses.Count -ne 0) { $true } else {$false} }) } }

} $ApiUrl=$Response.'@odata.nextlink' }

$Result | Export-CSV "D:\O365 Last Logon.csv" -NoTypeInformation -Encoding UTF8

I need a help ASAP please.

Thanks.

Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
12,015 questions
Microsoft Entra ID
Microsoft Entra ID
A Microsoft Entra identity service that provides identity management and access control capabilities. Replaces Azure Active Directory.
21,729 questions
{count} votes

Accepted answer
  1. Chad Kennedy 95 Reputation points
    2023-03-27T12:56:29.0366667+00:00

    It looks like they made a change to the $top parameter and we are limited to 120 users at a time now. Try to change that script from 999 to 120, that resolved it for me.

    3 people found this answer helpful.

2 additional answers

Sort by: Most helpful
  1. A.Elrayes 186 Reputation points
    2023-03-26T11:58:39.5433333+00:00

    @Patchfox I can't find this attribute "signInActivity" in users properties even by powershell !!

    0 comments No comments

  2. CarlZhao-MSFT 41,941 Reputation points
    2023-03-27T08:50:44.2033333+00:00

    Hi @A.Elrayes

    This is because your tenant lacks the Azure AD Premium P1/P2 license. Refer to the official documentation:

    User's image

    Hope this helps.

    If the reply is helpful, please click Accept Answer and kindly upvote it. If you have additional questions about this answer, please click Comment.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.