Get users who haven’t logged in longer than X days (LastLogonDate)

This script might be useful in getting users that haven’t logged for a longer amount of time. It is checking lastlogondate property:

Get-ADUser -Identity $Env:username -Properties 'Name','Enabled','WhenCreated','LastLogonDate','lastlogontimestamp','PasswordExpired'

lastlogondate

Please be aware that it gets a date only from the specified Domain Controller. In this case, I added a logon server in the server parameter and I was looking only for enabled users in People OU.

Below you can find the final script for getting users who haven’t logged in longer than 30 days. It will save results to CSV file on your desktop and finally, in the end, it will open results in a new pop-up window.

        #Import Modules ##########################################################         
        Try{
            Import-Module ActiveDirectory -ErrorAction Stop
        }
        Catch{
            Write-Warning $_.Exception.Message
            Read-Host "Script will end. Press enter to close the window"
            Exit
        }
  
  
        #Params ##################################################################
        $LastLogon   = (Get-Date).AddDays(-30).ToFileTime()
        $ReportPath  = "$env:userprofiledesktop"
        $FileDate    = Get-Date -Format "yyyyMMddHHmmss"
        $OutputCsv   = "$ReportPathLastLogonDate_users_$FileDate.csv" 
  
  
        # Query params ############################################################## 
        $Params = @{
            LDAPFilter   = "(&(objectclass=user)(useraccountcontrol=512)(lastlogontimestamp<=$LastLogon))"
            Server       = ($env:LOGONSERVER -replace "\",'')
            SearchBase   = 'OU=People,DC=powershellbros,DC=com'
            Properties   = 'Name','Enabled','WhenCreated','LastLogonDate','lastlogontimestamp','PasswordExpired'
        }
  
  
        #Get all ENABLED users from OU ####################################
        Get-ADUser @Params | Select Name,
                                    Enabled,
                                    whenCreated,
                                    lastlogondate,
                                    PasswordExpired | Export-Csv $OutputCsv -NoTypeInformation 
  
  
        #Import CSV and display results ##########################################
        Import-CSV $OutputCsv | Out-GridView -Title 'Users > 30days'

Leave a Reply

Your email address will not be published. Required fields are marked *