62 lines
2.5 KiB
PowerShell
62 lines
2.5 KiB
PowerShell
# Remove AD `howard` account (misspelled/orphan account, not used by anyone).
|
|
# Captures pre-state to D:\Backups and confirms removal. AD Recycle Bin keeps
|
|
# the object for 180 days so Restore-ADObject is available if needed.
|
|
|
|
$ErrorActionPreference = 'Stop'
|
|
Import-Module ActiveDirectory
|
|
|
|
$ts = Get-Date -Format 'yyyy-MM-dd-HHmmss'
|
|
$bd = "D:\Backups\howard-delete-$ts"
|
|
New-Item -Path $bd -ItemType Directory -Force | Out-Null
|
|
|
|
try {
|
|
$u = Get-ADUser -Identity howard -Properties *
|
|
Write-Output 'Pre-delete state:'
|
|
Write-Output " SAM: $($u.SamAccountName)"
|
|
Write-Output " UPN: $($u.UserPrincipalName)"
|
|
Write-Output " Display: $($u.DisplayName)"
|
|
Write-Output " Description: $($u.Description)"
|
|
Write-Output " mail: $($u.mail)"
|
|
Write-Output " proxyAddrs: $(($u.proxyAddresses) -join '; ')"
|
|
Write-Output " DN: $($u.DistinguishedName)"
|
|
Write-Output " Enabled: $($u.Enabled)"
|
|
Write-Output " PwdLastSet: $($u.PasswordLastSet)"
|
|
Write-Output " Created: $($u.whenCreated)"
|
|
Write-Output ''
|
|
Write-Output ' Group memberships:'
|
|
Get-ADPrincipalGroupMembership -Identity howard | ForEach-Object {
|
|
Write-Output " - $($_.Name)"
|
|
}
|
|
|
|
$u | Export-Clixml "$bd\howard-pre.xml"
|
|
Write-Output ''
|
|
Write-Output "Pre-state exported to: $bd\howard-pre.xml"
|
|
Write-Output ''
|
|
Write-Output 'Removing AD user howard...'
|
|
Remove-ADUser -Identity howard -Confirm:$false
|
|
Write-Output '[OK] Remove-ADUser returned without error.'
|
|
|
|
Write-Output ''
|
|
Write-Output 'Verifying removal:'
|
|
try {
|
|
Get-ADUser -Identity howard -ErrorAction Stop | Out-Null
|
|
Write-Output '[FAIL] Account still exists'
|
|
exit 1
|
|
} catch {
|
|
Write-Output "[OK] Get-ADUser -Identity howard returns: $($_.Exception.Message.Split([char]10)[0])"
|
|
}
|
|
|
|
Write-Output ''
|
|
Write-Output 'Recycle Bin (180 day retention) entry for rollback:'
|
|
$deleted = Get-ADObject -Filter { SamAccountName -eq 'howard' } -IncludeDeletedObjects -Properties whenChanged, isDeleted, ObjectGUID, lastKnownParent
|
|
$deleted | Select-Object Name, ObjectGUID, isDeleted, whenChanged, lastKnownParent | Format-List | Out-String | Write-Output
|
|
Write-Output 'Rollback command (within 180 days):'
|
|
if ($deleted) {
|
|
$guid = $deleted | Select-Object -First 1 -ExpandProperty ObjectGUID
|
|
Write-Output " Restore-ADObject -Identity $guid"
|
|
}
|
|
} catch {
|
|
Write-Output "FAIL: $_"
|
|
exit 1
|
|
}
|