Difference between revisions of "Inactive AD accounts"
Jump to navigation
Jump to search
Line 26: | Line 26: | ||
Write-Error "Failed to disable account: $username. Error: $_" | Write-Error "Failed to disable account: $username. Error: $_" | ||
} | } | ||
+ | } | ||
+ | ``` | ||
+ | |||
+ | # Remove user and remove SID from all AD Groups | ||
+ | ``` | ||
+ | # Define the username of the account to be removed | ||
+ | $username = "username_to_remove" | ||
+ | |||
+ | # Get the user account | ||
+ | $user = Get-ADUser -Identity $username | ||
+ | |||
+ | if ($user) { | ||
+ | # Get all groups the user is a member of | ||
+ | $groups = Get-ADUser -Identity $username -Property MemberOf | Select-Object -ExpandProperty MemberOf | ||
+ | |||
+ | # Remove the user from each group | ||
+ | foreach ($group in $groups) { | ||
+ | Remove-ADGroupMember -Identity $group -Members $user -Confirm:$false | ||
+ | } | ||
+ | |||
+ | # Remove the user account from AD | ||
+ | Remove-ADUser -Identity $username -Confirm:$false | ||
+ | |||
+ | Write-Output "User $username has been removed from all groups and deleted from AD." | ||
+ | } else { | ||
+ | Write-Output "User $username not found in AD." | ||
} | } | ||
``` | ``` |
Revision as of 15:13, 19 August 2024
Get inactive accounts
Import-Module ActiveDirectory $ouPath = "OU=Some Accounts,DC=example,DC=com" $usersNoPasswordReset = Get-ADUser -Filter { PasswordLastSet -gt "7/11/2023 00:00:00 AM" -and LastLogonDate -lt "7/11/2023 00:00:00 AM" -and SamAccountName -like "somesvc-*" -and Enabled -eq $true } -SearchBase $ouPath -Properties PasswordLastSet, LastLogonDate, Enabled | Select-Object Name, SamAccountName, PasswordLastSet, LastLogonDate, Enabled $usersNoPasswordReset | Format-Table -AutoSize
Import-Module ActiveDirectory $textFilePath = "users.txt" $usernames = Get-Content -Path $textFilePath foreach ($username in $usernames) { try { Disable-ADAccount -Identity $username -ErrorAction Stop # Remove-ADUser -Identity $username -Confirm:$false -ErrorAction Stop Write-Output "Disabled account: $username" } catch { Write-Error "Failed to disable account: $username. Error: $_" } }
Remove user and remove SID from all AD Groups
# Define the username of the account to be removed $username = "username_to_remove" # Get the user account $user = Get-ADUser -Identity $username if ($user) { # Get all groups the user is a member of $groups = Get-ADUser -Identity $username -Property MemberOf | Select-Object -ExpandProperty MemberOf # Remove the user from each group foreach ($group in $groups) { Remove-ADGroupMember -Identity $group -Members $user -Confirm:$false } # Remove the user account from AD Remove-ADUser -Identity $username -Confirm:$false Write-Output "User $username has been removed from all groups and deleted from AD." } else { Write-Output "User $username not found in AD." }