Created
September 20, 2024 18:18
-
-
Save dpo007/d967773c726876a28b0f0e2e3f9e7449 to your computer and use it in GitHub Desktop.
Removes a named GPO (and associated links) from multiple trusted domains
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
# Define the GPO name and the domains | |
$gpoName = "GPO To Go" | |
$domains = @("domain1.local", "domain2.local", "anotherDomain.com") | |
foreach ($domain in $domains) { | |
# Get the GPO | |
$gpo = Get-GPO -Name $gpoName -Domain $domain -ErrorAction SilentlyContinue | |
if ($gpo) { | |
# Get all OUs in the domain | |
$ous = Get-ADOrganizationalUnit -Filter * -SearchBase "DC=$($domain -replace '\.', ',DC=')" | |
# Include the root of the domain | |
$root = "DC=$($domain -replace '\.', ',DC=')" | |
$targets = $ous.DistinguishedName + $root | |
foreach ($target in $targets) { | |
try { | |
# Attempt to remove the link to the GPO with error suppression | |
Remove-GPLink -Name $gpoName -Target $target -Domain $domain -ErrorAction Stop 2>$null | |
Write-Output "Removed link to GPO '$gpoName' from '$target'." | |
} catch { | |
# Do nothing and continue the loop | |
} | |
} | |
# Delete the GPO | |
Remove-GPO -Guid $gpo.Id -Domain $domain | |
Write-Output "Deleted GPO '$gpoName' from domain '$domain'." | |
} else { | |
Write-Output "GPO '$gpoName' does not exist in domain '$domain'." | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment