GPOs: List-GPOs-EnabledandLinked-AndBackup

How to backup the Group Policies you are actually using

'List-GPOs-EnabledandLinked-AndBackup.ps1'
# Import the GroupPolicy module
Import-Module GroupPolicy -verb

# ------------------------------------------------------------
# CONFIGURATION
# ------------------------------------------------------------

# Base path where all backups will be stored
$RootBackupPath = 'D:\GPOEnabledAndLinked'

# ------------------------------------------------------------
# SCRIPT
# ------------------------------------------------------------

# 1) Remove existing backups in the target directory
if (Test-Path $RootBackupPath) {
    Write-Host "Removing existing backups in `"$RootBackupPath`" …"
    Remove-Item "$RootBackupPath\*" -Recurse -Force -Verbose -ErrorAction SilentlyContinue
}

Write-Host "Creating fresh backup directory at `"$RootBackupPath`" …"
New-Item -Path $RootBackupPath -ItemType Directory -ErrorAction SilentlyContinue | Out-Null

# 2) Check and back up linked GPOs
Write-Host "Backing up linked GPOs to `"$RootBackupPath`" …"

# Get all GPOs that are enabled
$gpos = Get-GPO -All | Where-Object { $_.GpoStatus -ne "AllDisabled" }

foreach ($gpo in $gpos) {
    # Generate a report for GPO in XML format
    $gpoReport = Get-GPOReport -Guid $gpo.Id -Domain 'wcnet.co.warren.nj.us' -ReportType XML
    
    # Ensure the report is not empty
    if ($gpoReport) {
        # Load the XML to check for linked OUs
        [xml]$xmlReport = $gpoReport

        # Check if the GPO is linked to any OUs or sites
        $linkedLocations = $xmlReport.DocumentElement.LinksTo.SOMPath #<--VERY important part

        # Backup the GPO only if it is linked
        if ($linkedLocations.Count -gt 0) {
            Backup-GPO -Guid $gpo.Id -Path $RootBackupPath `
                -Comment ("Full backup taken on {0:u}" -f (Get-Date))
            Write-Host "Backed up GPO: $($gpo.DisplayName) linked to the following locations:"
            foreach ($link in $linkedLocations) {
                Write-Host "  - $($link.Name)"
            }
        } else {
            Write-Host "Skipped GPO (not linked): $($gpo.DisplayName)"
        }
    } else {
        Write-Host "Failed to generate report for: $($gpo.DisplayName)"
    }
}

Write-Host "Backup of linked GPOs completed. Check: $RootBackupPath"

Posted

in

,

by

Comments

One response to “GPOs: List-GPOs-EnabledandLinked-AndBackup”

  1. […] and then run the backup again filtering for only linked policiesHere’s a clue: see the GPOs: List-GPOs-EnabledandLinked-AndBackup […]