Auditing Active Directory is a critical task for monitoring and maintaining security within your Windows environment. Below is a PowerShell script that can be used to audit Active Directory. This script will generate a report of user accounts that haven’t logged in for a specified period and accounts that have expired passwords.
# Define the path where you want to save the audit report
$reportPath = "C:\Audit\AD_Audit_Report.csv"
# Define the number of days to check for inactive accounts
$inactiveDays = 90
# Get the current date
$currentDate = Get-Date
# Calculate the date for the threshold (90 days ago)
$thresholdDate = $currentDate.AddDays(-$inactiveDays)
# Get inactive user accounts
$inactiveUsers = Get-ADUser -Filter {LastLogonDate -lt $thresholdDate} -Properties LastLogonDate | Select-Object SamAccountName, Name, LastLogonDate
# Get user accounts with expired passwords
$expiredPasswords = Get-ADUser -Filter {Enabled -eq $true -and PasswordNeverExpires -eq $false -and (PasswordLastSet -lt (Get-Date).AddDays(-90))} -Properties PasswordLastSet | Select-Object SamAccountName, Name, PasswordLastSet
# Create an empty array to store the results
$results = @()
# Add the inactive users to the results array
foreach ($user in $inactiveUsers) {
$results += [PSCustomObject]@{
"User" = $user.SamAccountName
"Name" = $user.Name
"LastLogonDate" = $user.LastLogonDate
"Status" = "Inactive"
}
}
# Add the users with expired passwords to the results array
foreach ($user in $expiredPasswords) {
$results += [PSCustomObject]@{
"User" = $user.SamAccountName
"Name" = $user.Name
"PasswordLastSet" = $user.PasswordLastSet
"Status" = "Password Expired"
}
}
# Export the results to a CSV file
$results | Export-Csv -Path $reportPath -NoTypeInformation
# Display a message indicating the completion of the audit
Write-Host "Active Directory audit completed. Report saved to: $reportPath"
Here’s what the script does:
- Define the path where you want to save the audit report, the number of days to check for inactive accounts (
$inactiveDays
), and the current date. - Calculate a threshold date (
$thresholdDate
) based on the specified number of inactive days. - Use
Get-ADUser
to retrieve inactive users (accounts that haven’t logged in since the threshold date) and users with expired passwords. - Create an empty array (
$results
) to store the results. - Add the inactive users and users with expired passwords to the results array.
- Export the results to a CSV file.
- Display a message indicating the completion of the audit.
Modify the script as needed to fit your specific requirements, such as adjusting the threshold for inactive accounts or changing the report path.