Powershell : Clean of unlinked GPO objects

This is a follow post from the article I did here 

This applies when you have a list of GPO's that are not applied and you wish to purge them, or delete them, now deleting GPO files is not a small task and I will strongly suggest you have a backup of these objects before you delete them, if you need help with that check this out here

WARNING : This script will delete GPO objects ensure you have a backup and ensure you have a exceptions file that is valid and contains the name of the GPO object correctly.

Disclaimer : The blog author cannot be held responsible for the incorrect usage of script, you should understand what the script does, before you run a script you "found on the internet"

# Get all Group Policy objects
Write-Host "Getting all Group Policy objects..."

$GroupPolicies = Get-GPO -All

# Array to store unlinked Group Policy names
$UnlinkedPolicies = @()

# Read exclusion text file
$ExclusionList = Get-Content -Path "ExcludedGPO.txt"

# Loop through each Group Policy object
foreach ($Policy in $GroupPolicies) {
    # Check if the Group Policy is linked to any Organizational Unit
    Write-Host "Checking Group Policy: $($Policy.DisplayName)"
    $LinkedOU = Get-GPOReport -Name $Policy.DisplayName -ReportType XML | Select-String -Pattern "<LinksTo>" -SimpleMatch

    # If not linked, add the Group Policy name to the array if it's not in the exclusion list
    if (!$LinkedOU) {
        Write-Host "Group Policy $($Policy.DisplayName) is not linked to any Organizational Unit."
        if ($ExclusionList -notcontains $Policy.DisplayName) {
            $UnlinkedPolicies += $Policy.DisplayName
        }
    } else {
        Write-Host "Group Policy $($Policy.DisplayName) is linked to one or more Organizational Units."
    }
}

# Output the list of unlinked Group Policy names
Write-Host "`nUnlinked Group Policies:`n"
$UnlinkedPolicies

# Delete unlinked Group Policies except those in the exclusion list
foreach ($PolicyName in $UnlinkedPolicies) {
    if ($ExclusionList -notcontains $PolicyName) {
        #Remove-GPO -Name $PolicyName -Confirm:$false
        Write-Host "Deleted Group Policy: $PolicyName"
    }
}

Note : You will need to remove the # that is before the Remove-GPO, that is there as an extra failsafe from people ignoring the warning and disclaimer.

Previous Post Next Post

Ω†Ω…ΩˆΨ°Ψ¬ Ψ§Ω„Ψ§ΨͺΨ΅Ψ§Ω„