Wednesday 26 June 2024

HOW TO FIND INACTIVE USER ACCOUNT ON ACTIVE DIRECTORY USING POWERSHELL

Hi there,

If you are looking to tidy up your Active Directory by finding inactive accounts, I have a PowerShell script that can do just that. Save and run this script on your domain controller. This is just a audit tool and wont delete any thing.

  1. Save the code with a ".PS1" extension.
  2. Open PowerShell as an admin and run the script.


    Clear-Host

    Write-Host -ForegroundColor yellow " FIND INACTIVE USERS/STALE USER"

    # Import the Active Directory module
    Import-Module ActiveDirectory

    # Prompt the user for the number of days
    $daysInactive = Read-Host "Enter the number of days for inactive accounts"

    # Calculate the date
    $timeSpan = (Get-Date).AddDays(-$daysInactive)

    # Search for inactive user accounts
    $inactiveAccounts = Get-ADUser -Filter {LastLogonDate -lt $timeSpan -and Enabled -eq $true} -Property LastLogonDate, DistinguishedName |
    Select-Object Name, SamAccountName, LastLogonDate, DistinguishedName

    # Check if any inactive accounts were found
    if ($inactiveAccounts.Count -eq 0) {
    Write-Host "No inactive accounts found."
    } else {
    # Display the inactive accounts in a grid view
    $inactiveAccounts | Out-GridView -Title "Inactive User Accounts"
    }

No comments:

Post a Comment