-
-
Save giridharvedula/1b98674f20510c5ea5aa037f4a2a1156 to your computer and use it in GitHub Desktop.
PowerShell: Cleanup empty AD OUs
This file contains hidden or 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