Skip to content

Instantly share code, notes, and snippets.

@9to5IT
Created July 4, 2016 12:09
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save 9to5IT/8698b46b89d39db9174ce4cc4b1667cd to your computer and use it in GitHub Desktop.
Save 9to5IT/8698b46b89d39db9174ce4cc4b1667cd to your computer and use it in GitHub Desktop.
PowerShell: Cleanup empty AD OUs
Import-Module ActiveDirectory
#-------------------------------
# FIND EMPTY OUs
#-------------------------------
# Get empty AD Organizational Units
$OUs = Get-ADOrganizationalUnit -Filter * | ForEach-Object { If ( !( Get-ADObject -Filter * -SearchBase $_ -SearchScope OneLevel) ) { $_ } } | Select-Object Name, DistinguishedName
#-------------------------------
# REPORTING
#-------------------------------
# Export results to CSV
$OUs | Export-Csv C:\Temp\InactiveOUs.csv -NoTypeInformation
#-------------------------------
# INACTIVE OUs MANAGEMENT
#-------------------------------
# Delete Inactive OUs
ForEach ($Item in $OUs){
Remove-ADOrganizationalUnit -Identity $Item.DistinguishedName -Confirm:$false
Write-Output "$($Item.Name) - Deleted"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment