Created
January 12, 2018 17:27
-
-
Save VimalShekar/4af795ab2e1d2ab48662c503fe6321a1 to your computer and use it in GitHub Desktop.
Delete a GPO and remove any linkages
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
# Adding as GIST, to make it easier to link to my blog. | |
# Visit: vimalshekar.ml for more interesting scripts. | |
# | |
# If given GPO is linked to any OU, it deletes the links and then attempts to delete the GPO. | |
# | |
function Delete-GPOByName | |
{ | |
param( | |
[string]$GPOName, | |
[string]$DomainName | |
) | |
$error.clear() | |
$MyGpo = New-Object -comObject GPMgmt.GPM | |
Write-host "Delete-GPOByName: Created new GPM object" | |
$MyGPConstants = $MyGpo.GetConstants() | |
$MyGPDomain = $MyGpo.GetDomain($DomainName, "", $MyGPConstants.UseAnyDc) | |
Write-host "Delete-GPOByName: Created new GPDomain object" | |
$SearchCriteria = $MyGpo.CreateSearchCriteria() | |
$SearchCriteria.Add($MyGPConstants.SearchPropertyGPODisplayName, $MyGPConstants.SearchOpEquals, $GPOName) | |
$SearchResults = $MyGPDomain.SearchGPOs($SearchCriteria) | |
Write-host "Delete-GPOByName: Search to find $GPOName returned $($SearchResults.Count) results" | |
foreach($GPO in $SearchResults ) { | |
$SafeTodeleteGPO = $true; | |
Write-host "Delete-GPOByName: GPO ID for $GPOName is $($GPO.ID)" | |
$GPMGPO = $MyGPDomain.GetGPO($GPO.ID) | |
$SearchCriteria1 = $MyGpo.CreateSearchCriteria() | |
$SearchCriteria1.Add($MyGPConstants.SearchPropertySOMLinks, $MyGPConstants.SearchOpContains, $GPMGPO) | |
$SearchResults1 = $MyGPDomain.SearchSOMs($SearchCriteria1) | |
Write-host "Delete-GPOByName: Search to find links returned $($SearchResults1.Count) results" | |
foreach($link in $SearchResults1) { | |
Write-Host $link.Path | |
$GPOLinks = $link.GetGPOLinks() | |
foreach($gpolink in $GPOLinks) { | |
if($gpolink.GPOID -eq $GPO.ID) | |
{ | |
Write-host "Delete-GPOByName: Found link for $($GPO.ID), deleting link" | |
try { | |
$gpolink.delete() | |
Write-host "Delete-GPOByName: Link deleted successfully" | |
} | |
catch { | |
Write-host "Delete-GPOByName: Exception during delete operation" | |
$SafeTodeleteGPO = $false | |
} | |
} | |
} | |
} | |
if($SafeTodeleteGPO) | |
{ | |
Write-host "Delete-GPOByName: Safely deleting GPO" | |
try { | |
$GPMGPO.Delete() | |
Write-host "Delete-GPOByName: GPO deleted successfully" | |
} | |
catch { | |
Write-host "Delete-GPOByName: Exception during delete operation" | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment