Skip to content

Instantly share code, notes, and snippets.

@VimalShekar
Created January 15, 2018 17:14
Show Gist options
  • Save VimalShekar/adb77ebaf6c5ca3fd25b0ec656465a81 to your computer and use it in GitHub Desktop.
Save VimalShekar/adb77ebaf6c5ca3fd25b0ec656465a81 to your computer and use it in GitHub Desktop.
Unlink a GPO and delete it.
#
# 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"
}
}
}
}
# Sample Usage:
# Delete-GPOByName -GPOName "NewTest GPO" -DomainName "testdom.com"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment