Forum Discussion
StevenRPF
Mar 02, 2023Brass Contributor
Export list users never loged in
I'm trying to use this script I've found on the internet :
#Set admin UPN
$UPN = 'email address removed for privacy reasons'
#Time range
$startDate = (Get-Date).AddDays(-30).ToString('MM/dd/yyyy')
$endDate = (Get-Date).ToString('MM/dd/yyyy')
#We are looking for accounts that are active - not deactivated
$allUsers = @()
$allUsers = Get-MsolUser -All -EnabledFilter EnabledOnly | Select UserPrincipalName
#We search
$loggedOnUsers = @()
$loggedOnUsers = Search-UnifiedAuditLog -StartDate $startDate -EndDate $endDate -Operations UserLoggedIn, PasswordLogonInitialAuthUsingPassword, UserLoginFailed -ResultSize 5000
#Create the list
$inactiveInLastSixMonthsUsers = @()
$inactiveInLastSixMonthsUsers = $allUsers.UserPrincipalName | where {$loggedOnUsers.UserIds -NotContains $_}
#We get a result
Write-Output "The following users have no logged in for the last 180 days:"
#written to the screen
Write-Output $inactiveInLastSixMonthsUsers
#Export list to CSV
$inactiveInLastSixMonthsUsers
$inactiveInLastSixMonthsUsers > "C:\Temp\InactiveUsers.csv"
dont know why, but this command never return any data in the variable :
$loggedOnUsers = Search-UnifiedAuditLog -StartDate $startDate -EndDate $endDate -Operations UserLoggedIn, PasswordLogonInitialAuthUsingPassword, UserLoginFailed -ResultSize 5000
When I check other variable, I get info, but this one never return anything. I tried with different option and nothing ... that's where my problem is.
Any suggestion would be appreciate, or if you have another solution to find all users in the tenant that never loged in, that's what I need!
Thanks!
Try this, to check user account under 'enable' condition, but never logged on or not logged in 60 days
Get-ADUser -Filter { Enabled -eq $True } -Properties LastLogonDate | #Tests whether LastLogonDate is older than 60 days or if it's $Null Where-Object { $_.LastLogonDate -lt (Get-Date).AddDays(-60) -or -not $_.LastLogonDate } | Select-Object -Property SamAccountName | Format-Table