One of the most common task in Active Directory is finding inactive AD users on regular basis to disable or delete staled accounts from Active Directory. In powershell, we can use the cmdlet Get-ADUser to get set of user details. We can use either SQL like filter or LDAP filter with lastLogonTimeStamp attribute to get inactive users.
Find and List Inactive AD Users
We can find all inactive AD users for the specified time period by comparing user’s lastlogontimestamp value. The below powershell script find and list AD users who are not logged in last 90 days, it also filters disabled users and get only enabled inactive users.
Import-Module ActiveDirectory # No of days - Get AD users who are no logged in last 90 days $DaysInactive = 90 $time = (Get-Date).Adddays(-($DaysInactive)) Get-ADUser -Filter {LastLogonTimeStamp -lt $time -and enabled -eq $true} -Properties *| Select-Object Name, @{Name="LastLogonTimeStamp"; Expression={[DateTime]::FromFileTime($_.lastLogonTimestamp).ToString()}}
Export Inactive AD Users to CSV file
We can generate and export Active Directory inactive users report to CSV file using Powershell cmdlets Get-ADUser and Export-CSV. You can add more attributes in Select-Object field to export more AD attributes of inactive users.
Import-Module ActiveDirectory # No of days - Get AD users who are no logged in last 90 days $DaysInactive = 90 $time = (Get-Date).Adddays(-($DaysInactive)) Get-ADUser -Filter {LastLogonTimeStamp -lt $time -and enabled -eq $true} -Properties * | Select-Object Name,Mail,DistinguishedName, @{Name="LastLogonTimeStamp"; Expression={[DateTime]::FromFileTime($_.lastLogonTimestamp).ToString()}} | # Export Inactive Users Report to CSV file Export-CSV "C:\InactiveADUsers.csv" -NoTypeInformation -Encoding UTF8
Export Inactive AD Users from Specific OU
We can set target OU scope by using the parameter SearchBase. The following powershell script select all the Inactive AD users from the Organization Unit ‘TestOU’ and export it to CSV file.
Import-Module ActiveDirectory # No of days - Get AD users who are no logged in last 90 days $DaysInactive = 90 $time = (Get-Date).Adddays(-($DaysInactive)) Get-ADUser -SearchBase "OU=TestOU,DC=TestDomain,DC=Local"` -Filter {LastLogonTimeStamp -lt $time -and enabled -eq $true} -Properties * | Select-Object Name,Mail,DistinguishedName, @{Name="LastLogonTimeStamp"; Expression={[DateTime]::FromFileTime($_.lastLogonTimestamp).ToString()}} | Export-CSV "C:\InactiveADUsers.csv" -NoTypeInformation -Encoding UTF8
CSV output of Inactive AD Users Report
Advertisement