Powershell Script

PowerShell Script: Inactive Active Directory User Cleanup

PowerShell Script: Inactive Active Directory User Cleanup: Introduction

This script helps you identify inactive Active Directory user accounts and optionally disable or export them for auditing. It’s a valuable tool for maintaining security, reducing clutter, and ensuring that unused accounts aren’t left open.

Step-by-Step Instructions:

Update the Script with Your Information:

  • Days of Inactivity: Set how many days a user must be inactive to be flagged.
  • Action: Choose whether to export the list, disable accounts, or both.
  • Export File: Specify the path where the list of inactive users will be saved.

Run the Script:

You can run this script manually or schedule it with Task Scheduler to automate cleanup audits.

Open PowerShell on a domain-joined machine with appropriate AD permissions.

How to Use:

1. Copy and Paste the Script:

# This script is made by VxLogic
# For more information, visit our website or contact us directly.

# 1. Configuration
$daysInactive = 90
$exportCsvPath = "C:\Scripts\InactiveUsers.csv"
$disableAccounts = $true  # Set to $false if you only want to export

# 2. Get the date cutoff
$cutoffDate = (Get-Date).AddDays(-$daysInactive)

# 3. Fetch users
$inactiveUsers = Get-ADUser -Filter {(Enabled -eq $true) -and (LastLogonTimeStamp -like "*")} -Property DisplayName, SamAccountName, LastLogonTimeStamp | Where-Object {
    $lastLogon = [DateTime]::FromFileTime($_.LastLogonTimeStamp)
    $lastLogon -lt $cutoffDate
}

# 4. Export to CSV
$inactiveUsers | Select-Object DisplayName, SamAccountName, @{Name="LastLogon"; Expression={[datetime]::FromFileTime($_.LastLogonTimeStamp)}} |
    Export-Csv -Path $exportCsvPath -NoTypeInformation

Write-Host "Inactive users exported to $exportCsvPath"

# 5. Optional: Disable accounts
if ($disableAccounts -and $inactiveUsers.Count -gt 0) {
    foreach ($user in $inactiveUsers) {
        Disable-ADAccount -Identity $user.SamAccountName
        Write-Host "Disabled account: $($user.DisplayName)"
    }
} else {
    Write-Host "No accounts disabled. Set \$disableAccounts to \$true if desired."
}

PowerShell Script: Inactive Active Directory User Cleanup: Looking for More Solutions?

Need help maintaining your Active Directory or automating other IT tasks? Contact VxLogic today to see how we can streamline your IT operations.

Follow Us
Check out our Facebook and LinkedIn pages for more PowerShell scripts and automation tips.

Leave a Comment

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