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

Basic JavaScript: Understanding Case Sensitivity in Variables

// Declarationsvar StUdLyCapVaR;var properCamelCase;var TitleCaseOver;// AssignmentsSTUDLYCAPVAR = 10;PRoperCAmelCAse = "A String";tITLEcASEoVER = 9000;

PowerShell: Play with Time

1. Constructor: $timer=[System.Diagnostics.Stopwatch]::StartNew() 2. Accessing a property $totalSeconds=$timer.Elapsed.TotalSeconds 3. Output Time (Usage): $hours=[math]::round($totalSeconds/3600,2)write-host "It has…

PowerShell: Replacing Notepad with Notepad Plus Plus

Update 12/04/2020: there's a simpler solution - install notepad2! choco install notepad2 -y The command…