We use cookies to improve your experience.
By your continued use of this site you accept such use.
For more details please see our privacy policy and cookies policy.

Script repository

Check if account is inactive in Microsoft Entra ID longer than a period of time

February 21, 2024 Views: 1334

The script returns true if the account is inactive in Microsoft Entra ID longer than a period of time. The script can be executed in the If PowerShell script returns true condition of business rules, custom commands and scheduled tasks.

In the script, the $inactivityDurationThreshold variable specifies the inactivity duration in days that should be exceeded for the condition to be met.

Edit Remove
PowerShell
$inactivityDurationThreshold = 4 # TODO: modify me

# Get access token for Microsoft Graph API
$token = $Context.CloudServices.GetAzureAuthAccessToken()

# Get the last logon date
try
{
    $userId = [Guid]$Context.TargetObject.Get("adm-O365ObjectId")
}
catch
{
    $Context.ConditionIsMet = $False
    return # The user does not have a Microsoft 365 account.
}

$url = 'https://graph.microsoft.com/beta/users/' + $userId.ToString() + '?$select=signInActivity'
$response = Invoke-RestMethod -Method GET `
    -uri $url `
    -Headers @{Authorization="Bearer $token"}

if ([System.String]::IsNullOrEmpty($response.signInActivity.lastSignInDateTime))
{
    $Context.ConditionIsMet = $False
    return # The user never logged in to Microsoft Entra ID
}

$lastLogonDate = [System.DateTime]$response.signInActivity.lastSignInDateTime

# Get current date
$currentDate = [System.DateTime]::Now

# Substract the number of days and compare dates
$Context.ConditionIsMet = $lastLogonDate -lt $currentDate.AddDays(- $inactivityDurationThreshold)
Comments 0
Leave a comment
Loading...

Got questions?

Support Questions & Answers