I would like to output the list of users who have not logged in for more than a month to retrieve licenses. How can I obtain the last connection of users who have an AD license whose accounts are still active.
$guestuserIDs= (Get-AzureADUser -Filter "AccountEnabled eq true" | Select-Object ObjectId).ObjectId
$startTime = (get-date).AddDays(-30).ToString("yyyy-MM-dd")
foreach($guestUserID in $guestuserIDs){
Get-AzureADAuditSignInLogs -Filter "UserId eq '$guestUserID'" -Top 1 |Select-Object UserId,UserDisplayName,CreatedDateTime
}
I don't know how and if it's possible to add a command line to validate users who are currently consuming a license. Any help would be appreciate! Thanks
CodePudding user response:
Please check Below powershell commands which i tested in my environment:
To list users who have not logged in for more than a month and obtain the last connection/last logon of users who have AD license whose accounts are still enabled/active.
#Guest users Having account enabled and who are not logged in since last 30 days
$guestuserIDsLOGEDINLESSTHAN30DAYS= ((Get-AzureADUser -Filter "UserType eq
'Guest' and AccountEnabled eq true" )| Where-Object { $_.LastSignInDateTime -le (Get-Date).AddDays(-30) } )
$AllSiginLogs = Get-AzureADAuditSignInLogs -All $true
foreach($guestuser in $guestuserIDsLOGEDINLESSTHAN30DAYS)
{
$IsLicensed = if ($guestuser.assignedLicenses.Count -ne 0) { $true } else { $false }
#Below command gives last login time of users with license (having account enabled and who are not logged in since last 30 days)
if($IsLicensed)
{
$ObjectId=$guestuser.ObjectId
Write-Host "Displayname :" $guestuser.DisplayName " | IsAccountEnabled : " $guestuser.AccountEnabled " | ObjectId : " $guestuser.ObjectId " | UPN : " $guestuser.UserPrincipalName
Write-Host "IsLicensed :" $IsLicensed
#Below command gives last login time
$LoginRecord = $AllSiginLogs | Where-Object{ $_.UserId -eq $guestuser.ObjectId } | Sort-Object CreatedDateTime -Descending
if($LoginRecord.Count -gt 0){
$lastLogin = $LoginRecord[0].CreatedDateTime
}else{
$lastLogin = 'no login record'
}
Write-Host "Last logon time : " $lastLogin
Write-Host " "
#below commands `be used to get license details
$licenseDetails = Get-AzureADUserLicenseDetail -ObjectId $ObjectId
Write-Host "license COUNT : " $guestuser.assignedLicenses.Count
#Write-Host "license details : " $guestuser.AssignedLicenses
Write-Host "license details : " $licenseDetails
Write-Host " "
}
SAMPLE OUTPUT of last logon requirement: 
You can see below References to remove licenses if required for the above loop
- azuread-license-powershell-snippets
- Remove Microsoft 365 licenses from user accounts with PowerShell - | Microsoft Docs
Other references:
