Posted On February 6, 2020

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

kimconnect 0 comments
blog.KimConnect.com >> Codes >> 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 *

Related Post

PowerShell: Error Unable to find package provider ‘NuGet’ Resolved

How to install module in Powow Shill Current Version: $moduleCommand='New-SSHSession' $moduleName='Posh-SSH' if(!(get-command $moduleCommand -ea Ignore)){…

How To Add JavaScript Functions into WordPress

Assuming that the 'Code Snippets' plugin has already been installed, here's a demonstration of adding…

PowerShell: How to Replace a System File – For Experimentation Purposes

# When attempting to rename a system protected file such as notepad.exe $notepadExe='C:\Windows\system32\notepad.exe' $newNotePadExe='C:\Users\rambo\Desktop\notepad.exe' rename-item…