Report on domain users who have not logged in for 6 or more months and the accounts are active.

Kendra Whitcomb 20 Reputation points
2023-02-12T02:06:47.2766667+00:00

Looking to build a powershell script for an on-prem active directory environment. Need the following conditions:

  • Account is active
  • Last logon more than 6 months from current date
  • export to spreadsheet
  • list username, last logon date
Windows for business | Windows Client for IT Pros | Directory services | Active Directory
Windows for business | Windows Server | User experience | PowerShell
{count} votes

Accepted answer
  1. Fabricio Godoy 2,626 Reputation points
    2023-02-12T04:04:00.86+00:00

    Hey Kendra.

    I believe you are looking for this:

    # Get current date
    $currentDate = Get-Date
    
    # Get all users from the domain
    $users = Get-ADUser -Filter *
    
    # Create an array to store the filtered users
    $filteredUsers = @()
    
    # Loop through each user
    foreach ($user in $users) {
      # Check if the user account is active
      if ($user.Enabled -eq $true) {
        # Check if the last logon date is more than 6 months ago
        $lastLogon = [DateTime]::FromFileTime($user.LastLogonTimestamp)
        $monthsAgo = ($currentDate - $lastLogon).TotalDays / 30
    
        if ($monthsAgo -ge 6) {
          # Add the user to the filtered list
          $filteredUsers += New-Object PSObject -Property @{
            'Username' = $user.SamAccountName
            'Last Logon' = $lastLogon
          }
        }
      }
    }
    
    # Export the filtered users to a CSV file
    $filteredUsers | Export-Csv -Path "FilteredUsers.csv" -NoTypeInformation
    
    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.