Import-GphGpFromBackup.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
function Import-GphGpFromBackup
{
  <#
      .SYNOPSIS
      Import all GPO-Backups into a new domain
 
      .DESCRIPTION
      Import-GphGpFromBackup imports all Backups from a GPO-Folder into a new domain, using the
      original GPO Names. The Parameter -MigrationTablePath allows to use a Migration-Table for Import.
 
      .EXAMPLE
      Import-GphGpFromBackup -BackupPath c:\gpobackup -Description 'For Demo Purposes'
     
      Imports all GPOs from C:\gpoBackup into a new domain. The Backups are only imported, but not linked. All
      GPOs will inherit the Description "For Demo Purposes".
 
      .EXAMPLE
      Import-GphGpFromBackup -BackupPath c:\gpobackup -MigrationTablePath c:\gpobackup\Netzweise.migtable
     
      Imports all GPOs from C:\gpoBackup into a new domain, using the Migration-Table Netzweise.migtable to
      replace Groups and Path.
  #>



  param(
    # The Path to the Backups.
    [ValidateScript({ if ( -not ( Test-Path -Path $_ -PathType container )) { Throw 'The Backup-Path is invalid'}; $true })]
    [Parameter(mandatory=$true)]
    [string]$BackupPath,

    # A Description which will be added to every imported Policy
    [String]$Description,

    # The Path to the Migration-File
    [ValidateScript({ if ( -not ( Test-Path -Path $_ -PathType leaf )) { Throw 'The Path to the Migration Table is invalid'}; $true })]
    [string]$MigrationTablePath 
  )

    $BackupFolderList = Get-ChildItem -path $BackupPath | Where-Object { $_.name -Match '{[\dA-F]{8}(?:-[\dA-F]{4}){3}-[\dA-F]{12}}' }
    Foreach ( $BackupFolder in $BackupFolderList )
    {
        [xml]$BackupData = Get-Content -Path "$($BackupFolder.Fullname)\Backup.xml"
        $GroupPolicyName = ($BackupData.GroupPolicyBackupScheme.GroupPolicyObject.GroupPolicyCoreSettings.DisplayName)."#cdata-section"
        $ImportParameter = @{
            Path = $BackupPath 
            BackupId = [Guid][string]$BackupFolder 
            TargetName = $GroupPolicyName 
            CreateIfNeeded = $true
        }
        If ( $MigrationTablePath)
        {
          $ImportParameter["MigrationTable"] =  $MigrationTablePath
        }
        # $GroupPolicyID = ($BackupData.GroupPolicyBackupScheme.GroupPolicyObject.GroupPolicyCoreSettings.ID)."#cdata-section"
        Import-GPO @ImportParameter | ForEach-Object -Process { $_.Description = "$Description`n" + $_.Description }
    }
}