Quicktip: Deleting Empty Groups via Powershell

Okay, you’ve done all your fact-finding. You have your huge list of groups that can be deleted from AD. You’ve dumped all membership to a file. Removed all members. Waited a few weeks for the screaming to stop and added back in the oopsies (and then you removed them from your master spreadsheet, right?).

Now it’s time to delete them all.

Same basic premise as the user removal one. A little more error checking/handling, since there’s no going back from this. Pop up window for confirmation, output file for results.


##import necessary modules and set window
##
import-module activedirectory
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")

##import CSV with groups to delete
##needs CN field
##
$Deletes=import-csv d:\groups\groupstodelete.csv

##set output
##
$output="d:\groups\results\Deleteresults.txt"
date|out-file $output

##Loop thru groups
##
foreach ($GGroup in $deletes){
 ## Reset variables
 ##
 $Testmembers = $Null
 $result=$null

 ##Set variables for groupname and msgbox
 ##
 $Groupname=$GGroup.cn
 $Messagebox="Proceed with removal of group `n`n"+$Groupname

##check if group has any members. if it does go to next in loop
 ##if it doesn't, begin processing.
 ##
 $GTestGroup=get-qadgroup $Groupname
 $TestMembers=$GTestGroup.allmembers
 if (!$Testmembers){
 "$Groupname is empty. `n`n"|out-file $output -append

##Perform the popup. If Yes is hit, will execute, otherwise will proceed
 ##
 $result = [System.Windows.Forms.MessageBox]::Show($Messagebox,"Confirm deletion", "YesNo" , "Information")
 if ($result -eq "Yes"){
 "Removal has been confirmed for $Groupname `n`n"|out-file $output -append
 ##Removing Group
 ##
 Start-Transcript -path $output -append

get-adgroup -identity $Groupname|remove-adgroup -confirm:$false
 ##get-adgroup -identity $Groupname|remove-adgroup -whatif
 stop-transcript
 }
 else {
 "$Groupname deletion not confirmed.Continuing. `n`n"|out-file $output -append
 continue
 }
 }
 else {
 "$Groupname is not empty. Please empty and continue `n`n"|out-file $output -append
 continue
 }
}

Script requires the AD & Quest AD Management Powershell modules to be installed

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s