|
| 1 | +# Load Active Directory Module |
| 2 | +Import-Module ActiveDirectory |
| 3 | + |
| 4 | +# Define timeframes |
| 5 | +$twoYearsAgo = (Get-Date).AddYears(-2) |
| 6 | +$oneYearAgo = (Get-Date).AddYears(-1) |
| 7 | +$sixMonthsAgo = (Get-Date).AddMonths(-6) |
| 8 | + |
| 9 | +# Output file paths |
| 10 | +$legacyAccountsFile = "C:\Temp\Reports_LegacyAccounts.csv" |
| 11 | +$inactiveAccountsFile = "C:\Temp\Reports_InactiveAccounts.csv" |
| 12 | + |
| 13 | +# Create arrays to store results |
| 14 | +$legacyAccountsResults = @() |
| 15 | +$inactiveAccountsResults = @() |
| 16 | + |
| 17 | +# Get legacy accounts |
| 18 | +Write-Output "Identifying legacy accounts..." |
| 19 | +$legacyAccounts = Get-ADUser -Filter * -Property WhenCreated, PasswordLastSet, PasswordNeverExpires, Enabled | Where-Object { |
| 20 | + $_.WhenCreated -lt $twoYearsAgo -and |
| 21 | + $_.PasswordLastSet -lt $oneYearAgo -and |
| 22 | + $_.PasswordNeverExpires -eq $true |
| 23 | +} |
| 24 | + |
| 25 | +# Collect legacy accounts into the results array |
| 26 | +foreach ($account in $legacyAccounts) { |
| 27 | + Write-Output "Legacy account found: $($account.SamAccountName)" |
| 28 | + $legacyAccountsResults += [PSCustomObject]@{ |
| 29 | + UserName = $account.SamAccountName |
| 30 | + DisplayName = $account.Name |
| 31 | + WhenCreated = $account.WhenCreated |
| 32 | + PasswordLastSet = $account.PasswordLastSet |
| 33 | + PasswordNeverExpires = $account.PasswordNeverExpires |
| 34 | + Enabled = $account.Enabled |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +# Get inactive accounts |
| 39 | +Write-Output "Identifying inactive accounts..." |
| 40 | +$inactiveAccounts = Get-ADUser -Filter * -Property LastLogonDate, Enabled | Where-Object { |
| 41 | + $_.LastLogonDate -lt $sixMonthsAgo -or |
| 42 | + $_.LastLogonDate -eq $null |
| 43 | +} |
| 44 | + |
| 45 | +# Collect inactive accounts into the results array |
| 46 | +foreach ($inactiveAccount in $inactiveAccounts) { |
| 47 | + Write-Output "Inactive account found: $($inactiveAccount.SamAccountName)" |
| 48 | + $inactiveAccountsResults += [PSCustomObject]@{ |
| 49 | + UserName = $inactiveAccount.SamAccountName |
| 50 | + DisplayName = $inactiveAccount.Name |
| 51 | + LastLogon = $inactiveAccount.LastLogonDate |
| 52 | + Enabled = $inactiveAccount.Enabled |
| 53 | + Status = "Inactive" |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +# Export results to CSV |
| 58 | +Write-Output "Exporting results to CSV files..." |
| 59 | +$legacyAccountsResults | Export-Csv -Path $legacyAccountsFile -NoTypeInformation -Encoding UTF8 |
| 60 | +$inactiveAccountsResults | Export-Csv -Path $inactiveAccountsFile -NoTypeInformation -Encoding UTF8 |
| 61 | + |
| 62 | +Write-Output "Reports generated:" |
| 63 | +Write-Output "Legacy Accounts Report: $legacyAccountsFile" |
| 64 | +Write-Output "Inactive Accounts Report: $inactiveAccountsFile" |
| 65 | + |
| 66 | +Write-Output "Script completed successfully." |
0 commit comments