Created
July 4, 2016 12:09
-
-
Save 9to5IT/8698b46b89d39db9174ce4cc4b1667cd to your computer and use it in GitHub Desktop.
PowerShell: Cleanup empty AD OUs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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