Skip to content

Dark Artistry

Menu
  • Home
  • My Art
  • Wallpaper
  • Linux Hardware
  • Privacy

Blog

Remove AD Accounts and User Share

January 12, 2021Category: PowerShell

A quick and dirty PowerShell Active Directory ‘AD’ account cleanup script that can be ran as a task in any domain. This program will remove AD accounts older than 90 days that are sitting in a disabled state. Hope it’s useful to someone looking for an example.

$ErrorActionPreference = 'SilentlyContinue'
<#
Account Cleanup Utility, 0.2
C. Nichols, 2021

Removes AD accounts older than 90 days including test and admin.
Removes the user's group memberships.
Removes the user's share folder.

The dangerous parts are currently commented out for safety.

ToDo
    Might need -Force on some commands.

Error Logging (Some-Command -ErrorVariable +CMDErrors):
    We can create an error variable to each command then write that var to an error log like so:

    PS C:\Users > $ErrorActionPreference = 'SilentlyContinue'
    PS C:\Users > Get-ChildItem -Path "e'\tesmp" -Recurse -ErrorVariable +CMDErrors
    PS C:\Users> ForEach ($err in $CMDErrors) { Write-Host $err }
    Cannot find path 'C:\Users\ \e'\' because it does not exist.
    $CMDErrors | Out-File -Append e:\junk\error.log
#>

<# ============================================================ #>

$ADMOU = "OU=Admins,DC=domain"
$PRDOU = "OU=Users,DC=domain"
$TSTOU = "OU=Users,DC=testdomain"

function Remove-Member {
    PARAM (
        [string]$Member,
        [Array]$Groups
    )

    ForEach ($MbrOf in $Groups) {
        #$CurrGroup = Get-ADGroup $MbrOf | Remove-ADGroupMember -Members $Member -Confirm:$false
        Write-Host "Removing $($Member) from Group $($MbrOf)"
    }
}

<# =========================== MAIN =========================== #>

$RmvList = New-Object -TypeName "System.Collections.ArrayList"
$UsrShare = New-Object -TypeName "System.Collections.ArrayList"
$UsrGroups = New-Object -TypeName "System.Collections.ArrayList"
$ReportLines = @()

$DDay = [DateTime]::Today.AddDays(-90) # go back 90 days: any account older than 90 gets collected.

<# ============================================================ #>

# extensionAttribute5 is an example filter that guarantees we only return employees.
$DisabledUsers = Get-ADUser -Filter {Enabled -EQ $false -AND extensionAttribute5 -EQ "e" -AND whenChanged -LE $DDay} -Properties samAccountName, extensionAttribute5, description, whenChanged, homeDirectory, memberof |
    Select samAccountName, extensionAttribute5, description, whenChanged, homeDirectory, memberof

ForEach ($Usr in $DisabledUsers) {

    [void]$RmvList.Add($Usr.samAccountName)
    [void]$UsrShare.Add($Usr.homeDirectory)

    # Remove user from groups.
    Remove-Member -Member $Usr.samAccountName -Groups $Usr.memberof
    $Admin = "$($Usr.samAccountName)_adm" # Let's pretend _adm is appended to the SAM account name for admins.
    $ADMINX = Get-ADUser -Filter {samAccountName -EQ $Admin} -SearchBase $ADMOU -Properties samAccountName, memberof |
        Select samAccountName, memberof

    if ($ADMINX -NE $Null) {
        [void]$RmvList.Add($Admin)
        Remove-Member -Member $ADMINX.samAccountName -Groups $ADMINX.memberof
    }
}

# Remove all old disabled accounts.
write-host "Total account(s) found: $($RmvList.Count)"

ForEach ($RUsr in $RmvList) {

    $DNProd  = "CN=$($Rusr),$($PRDOU)"
    $DNTest  = "CN=$($Rusr),$($TSTOU)"

    if ($RUsr.Contains("_")){
        $DNAdmin = "CN=$($Rusr),$($ADMOU)"
        Write-Host "Removing admin. $($DNAdmin)"
        #Remove-ADUser -Identity $DNAdmin
    } else {
        Write-Host "Removing prod account: $($DNProd)"
        Write-Host "Removing test account: $($DNTest)"
        #Remove-ADUser -Identity $DNProd
        #Remove-ADUser -Identity $DNTest
    }
    $ReportLines += $RUsr
}

# Delete user's H drive share.
ForEach ($Pth in $UsrShare) {

    $Share = $Pth.Split('\')[-1] # Get the share name only.

    Write-Host "Removing folder $($Pth)"
    #Remove-Item $HPath -Force -Recurse

    Write-Host "Removing share $($Share)"
    #Remove-SmbShare -Name $Name -Force
}

$RemovedAccounts = $ReportLines | Out-String
$Body = "Removed.`n$($RemovedAccounts)"
$Subj = "AD Account Cleanup Notification"
$From = "someone@somewhere"

$Addresses = @("you@somewhere")

ForEach ($To in $Addresses) {
    Write-Host "Sending mail to $($To)"
    #Send-MailMessage -From $From -To $To -Subject $Subj -Body $Body -SmtpServer "YOUR_SMTP_SERVER"
}
  • Click to share on X (Opens in new window) X
  • Click to share on Reddit (Opens in new window) Reddit
  • Click to share on Tumblr (Opens in new window) Tumblr
  • Click to share on Pocket (Opens in new window) Pocket
  • Click to share on Facebook (Opens in new window) Facebook
  • Click to share on Pinterest (Opens in new window) Pinterest

Like this:

Like Loading...
Posted in PowerShell, Programming, WindowsTagged active directory, ad account management, powershell
Mohawke

Mohawke

View Full Profile →

Recent Posts

  • A little dystopian reading for a dystopian future.
  • Omarchy Post Install on System 76 Laptop
  • Quick and dirty encrypted notepad in PowerShell
  • Simple Color Coded Log Tail Utility In PowerShell
  • Completely Wipe A Hard Drive With PowerShell

Categories

Links

  • Archive App
  • Archive Game
  • Archive OS
  • DistroWatch
  • FOSSHUB
  • FreeBSD
  • Freewear
  • HaikuOS
  • HelloTux
  • Kali Linux For "ethical" hackers
  • Parrot OS
  • Qubes Linux
  • Suckless
  • Tails Linux For Security and Privacy
  • W3C Free Detailed Coding Tutorials
Privacy Statement
GitHub
YouTube

Licensing
WTFPL
Stay Secure

SANS
Spamhaus
OpenSSF
Linux Security Advisory
privacy.net

Destruction of Democracy, Freedom, and Equality

Project 2025 Tracker
Action Tracker
Golf Tracker
Retribution Tracker
Tracking Trackers
Trump Wealth Tracker
Corruption Counter
Pardon Tracker (paid)

Real News
Secular Talk
Security, Privacy, & Open Source

EFF
EFF SLS
OSI
EPIC
NCA
Copyright © 2025 Dark Artistry. All Rights Reserved.
Screenr parallax theme by FameThemes
%d