Get a list of users in Active Directory who have not logged in for specified number of days using PowerShell

A client is currently in the planning stages of doing a migration to Azure AD and Office 365 and one of the things we needed was a list of users who have not logged on in the last few months but are still active in our AD.

Well it’s PowerShell to the rescue again (with Visual Studio Code my IDE of choice) with the following snippet of code which will query an AD environment looking for accounts which haven’t been touched in this case for 90 days and give me a nice CSV of their name and last logon timestamp.

import-module ActiveDirectory 
$domain = "adatum.com.au" 
$DaysInactive = 90
$time = (Get-Date).Adddays(-($DaysInactive))
 
# Get AD Users with lastLogonTimestamp less than time specified and is enabled
Get-ADUser -Filter {LastLogonTimeStamp -lt $time -and enabled -eq $true} -Properties LastLogonTimeStamp |
 
# Output Name and lastLogonTimestamp attributes into CSV
select-object Name,@{Name="Stamp"; Expression={[DateTime]::FromFileTime($_.lastLogonTimestamp).ToString('yyyy-MM-dd')}} | export-csv Inactive_Users.csv -notypeinformation

Save the above into a PS1 and then run this on a server which has the AD PowerShell modules (usually one of your DCs) and will then create a CSV located where the script is with a list of all the users who are still enabled but haven’t logged on in your environment.

7 Thoughts to “Get a list of users in Active Directory who have not logged in for specified number of days using PowerShell

  1. Thanks! Great job.

    Do you know how to disable these account that are not used since 90 days?

    Thanks a lot!

    1. Hey Farouk, something like the below should do what you’re after (not using the Quest AD module)…

      Get-ADUser -Properties name,lastLogonDate,mail -Filter * | Where { $_.lastLogonDate -lt (get-date).addmonths(-3) }

      1. Hey John, Thanks for your reply, this command can show me wich users are unused since 90 days but this don’t disable them right?

        I want to disable them by using something like this, but it show me an error with Identity parameter

        $user = Import-csv -path “C:\X\Disabled_Accounts.csv”

        forEach ($user in $users) {
        Disable-ADAccount -Identity $($user.samaccountname)
        }

        Regards

        Farouk

  2. Hi, Thanks for great share. Can you share me how to get the OU wise not for all domain wise.
    Can u guide on this

    1. Hi Sahul-
      You can add the -searchBase option:
      Get-ADUser -Properties name,lastLogonDate -Filter * -searchBase ‘OU=users,OU=enterprise,dc=thisDomain,dc=com’ | Where { $_.lastLogonDate -lt (get-date).adddays(-90) }

  3. If I wanted to sort the date on that export file by the oldest date at the top and the newest at the bottom, where would i place that sort command?

Leave a Reply to Farouk Cancel reply