Skip to content

Dark Artistry

Programming, Art, Linux, and Open Source

Menu
  • Home
  • My Art
  • Wallpaper
  • Free App List
  • Privacy

Remove AD Accounts and User Share

January 12, 2021

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 Twitter (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on Tumblr (Opens in new window)
  • Click to share on Pocket (Opens in new window)
  • Click to share on Facebook (Opens in new window)
  • Click to share on Pinterest (Opens in new window)

Like this:

Like Loading...
Tags: active directory, ad account management, powershell

Post navigation

Steam is a loss of freedom.
Manjaro Linux for Music Production

Mohawke

Technology junkie, artist, computer programmer, and supporter of open source.

Recent Posts

  • Containerize Calibre To Serve Up Your Books Using Podman.
  • A Short Story by OpenAI ChatGPT
  • PowerShell Code Written By ChatGPT AI.
  • Convert Apple HEIC to JPG on Linux with this simple Bash script.
  • PowerShell Configuration Storage Module

Categories

  • Art (16)
  • Artificial Intelligence (2)
  • DLang (1)
  • Example (7)
  • Games (7)
  • Graphics (16)
  • Gtk (4)
  • Hardware (14)
  • Linux (71)
  • Mac (24)
  • Misc (66)
  • Nim (2)
  • PowerShell (16)
  • Programming (60)
  • Python 3 (22)
  • Reviews (10)
  • Software (58)
  • Tutorials (39)
  • Windows (25)

Links

  • DistroWatch
  • FOSSHUB
  • Freewear
  • HelloTux
  • Kali Linux For "ethical" hackers
  • Manjaro
  • Native American Charities
  • Opera Web Browser Free VPN
  • Parrot OS
  • Plant Utopia
  • Tails Linux For Security and Privacy
  • VSCodium
  • Privacy Statement
Privacy Statement
Contact Me Directly
WTFPL
* Please consider donating.
First Nations
NAHA

Electronic Frontier Foundation

Open Source Initiative

Opensource.com

Linux Foundation

Ethical.net

© 2021-2023 Dark Artistry. Theme by Grace Themes
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept”, you consent to the use of ALL the cookies.
.
SettingsAccept
Privacy & Cookies Policy

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these cookies, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may have an effect on your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.
SAVE & ACCEPT
%d bloggers like this: