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: Process Watcher – Restart Stopped Services

# processWatcher.ps1 # User Input $computername=$env:computername $serviceName='remoteregistry' $desiredStatus='Running' $action={ param($serviceName) $erroractionpreference='stop' try{ start-service $serviceName return…

Listing SMB Shares on a Windows Machine

Option 1: PS C:\Windows\system32> get-WmiObject -class Win32_Share Name Path Description ---- ---- ----------- ADMIN$ C:\Windows…

PowerShell: removing elements of an immutable “fixed size” array

By default, PowerShell's Array is an object class; hence, its length a "fixed size" as…