Delete GPO (Perl)

This code can be found in Chapter 10 of Active Directory Cookbook, 2nd edition

Purchase XP Cookbook or Networking Recipes for only $25 plus shipping! While supplies last.

Find out how to download all of the Perl code from this site.

# This Perl code deletes the specified GPO.

# ---------------------------------------------------------------
# Adapted from VBScript code contained in the book:
#      "Active Directory Cookbook" by Robbie Allen
# ISBN: 0-596-00466-4
# ---------------------------------------------------------------

# ------ SCRIPT CONFIGURATION ------
my $strGPO      = "<GPOName>";        # e.g. My New GPO
my $strDomain   = "<DomainDNSName>";  # e.g. rallencorp.com
# ------ END CONFIGURATION ---------
use Win32::OLE;
$Win32::OLE::Warn = 3;
my $objGPM = Win32::OLE->CreateObject("GPMgmt.GPM");
my $objGPMConstants = $objGPM->GetConstants();
  
# Initialize the Domain $object
my $objGPMDomain = $objGPM->GetDomain($strDomain, "", $objGPMConstants->UseAnyDC);

# Find the GPO
my $objGPMSearchCriteria = $objGPM->CreateSearchCriteria;
$objGPMSearchCriteria->Add($objGPMConstants->SearchPropertyGPODisplayName,
                           $objGPMConstants->SearchOpEquals, $strGPO);
my $objGPOList = $objGPMDomain->SearchGPOs($objGPMSearchCriteria);
if ($objGPOList->Count == 0) {
   print "Did not find GPO: $strGPO\n";
   print "Exiting.\n";
   exit;
}
elsif ($objGPOList->Count > 1) {
   print "Found more than one matching GPO. Count: ", $objGPOList->Count,"\n";
   print "Exiting.\n";
   exit;
}
else {
   print "Found GPO: ", $objGPOList->Item(1)->DisplayName,"\n";
}

# Delete the GPO
$objGPOList->Item(1)->Delete;
print "Successfully deleted GPO: $strGPO\n";

This code has been viewed 1086 times.

New from the creators of TechTasks.com: StatSheet.com