PowerShell: Generate Report of Users and Computers That Have Not Logged On for X Days

# AccountsNotLoginXDays.ps1

# Set days
$lastLogonDaysExceeding = 120

# Gather Users
$daysRange = (get-date).adddays(-$lastLogonDaysExceeding)
$users=Get-ADUser -properties * -filter {(enabled -eq $True) -AND (lastlogondate -notlike "*" -OR lastlogondate -le $daysRange)} | sort -Property SAMaccountName;
[Array]$usersResult = for ($i=0;$i -lt $users.count;$i++){
$users[$i]|Select-Object @{name='Index';e={$i}},@{name='ObjectClass';e={'User'}},@{name='PrincipalId';e={$_.SAMaccountname}}, Name, passwordExpired, PasswordNeverExpires, logoncount, whenCreated, LastLogonDate;
}

$computers=Get-ADComputer -properties * -filter {(enabled -eq $True) -AND (lastlogondate -notlike "*" -OR lastlogondate -le $daysRange)} | sort -Property SAMaccountName;
$startingIndex=$usersResult.Count
[Array]$computersResult = for ($i=0;$i -lt $computers.count;$i++){
$index=$startingIndex+$i;
$computers[$i]|Select-Object @{name='Index';e={$index}},@{name='ObjectClass';e={'Computer'}},@{name='PrincipalId';e={$_.SAMaccountname}}, Name, passwordExpired, PasswordNeverExpires, logoncount, whenCreated, LastLogonDate;
}
$resultUsersAndComputers=$usersResult+$computersResult
$resultUsersAndComputers|ft -autosize;
$resultUsersAndComputers|export-csv c:\accountsNotLoginXdays.csv -NoTypeInformation

Leave a Reply

Your email address will not be published. Required fields are marked *