internal/functions/New-MigrationTable.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
function New-MigrationTable
{
<#
    .SYNOPSIS
        Creates a new migration table used for GPO imports.
     
    .DESCRIPTION
        Creates a new migration table used for GPO imports.
        In this table, all source identities get matched to fitting destination identities.
        This ensures, that all identity references within GPOs remain intact.
     
    .PARAMETER Path
        The path where to spawn the migration table.
        Specify a folder, the file will be named '<DomainName>.migtable'
     
    .PARAMETER BackupPath
        The path where the GPO backups are stored.
     
    .PARAMETER Domain
        The domain the backup will be restored to.
        Defaults to the current user's domain.
     
    .EXAMPLE
        PS C:\> New-MigrationTable -Path '.' -BackupPath '.'
     
        Creates a migration table in the current path and looks in the current path for backup folders.
#>

    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")]
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string]
        $Path,
        
        [Parameter(Mandatory = $true)]
        [string]
        $BackupPath,
        
        [string]
        $Domain = $env:USERDNSDOMAIN
    )
    
    begin
    {
        $resolvedPath = (Resolve-Path $Path).ProviderPath
        $resolvedBackupPath = (Resolve-Path $BackupPath).ProviderPath
        $writePath = Join-Path -Path $resolvedPath -ChildPath "$Domain.migtable"
        
        #region Resolving source and destination Domain Names
        $domainData = Get-DomainData -Domain $Domain
        $destDomainDNS = $domainData.Fqdn
        $destDomainNetBios = $domainData.ADObject.NetBIOSName
        
        if ($script:sourceDomainData)
        {
            $sourceDomainDNS = $script:sourceDomainData.DomainDNSName
            $sourceDomainNetBios = $script:sourceDomainData.NetBIOSName
        }
        elseif ($script:identityMapping.Count -gt 0)
        {
            $sourceDomainDNS = $script:identityMapping[0].DomainFqdn
            $sourceDomainNetBios = $script:identityMapping[0].DomainName
        }
        else
        {
            throw "Unable to determine source domain. Run Import-GptDomainData or Import-GptIdentity first!"
        }
        #endregion Resolving source and destination Domain Names
        
        #region Preparing imported identities
        $explicitIdentityMappings = foreach ($identity in $script:identityMapping)
        {
            if (($identity.IsBuiltIn -eq 'True') -and ($identity.SID -like "*-32-*"))
            {
                [PSCustomObject]@{
                    Source = $identity.Name
                    Target = $identity.Target
                }
            }
            else
            {
                [PSCustomObject]@{
                    Source = ('{0}\{1}' -f $identity.DomainName, $identity.Name)
                    Target = ('{0}\{1}' -f $identity.TargetDomain.Name, $identity.Target)
                }
                [PSCustomObject]@{
                    Source = ('{0}@{1}' -f $identity.Name, $identity.DomainFqdn)
                    Target = ('{0}@{1}' -f $identity.Target, $identity.TargetDomain.DNSRoot)
                }
            }
        }
        #endregion Preparing imported identities
    }
    process
    {
        #region Preparing basic migration table
        $groupPolicyManager = New-Object -ComObject GPMgmt.GPM
        $migrationTable = $groupPolicyManager.CreateMigrationTable()
        $constants = $groupPolicyManager.getConstants()
        $backupDirectory = $groupPolicyManager.GetBackupDir($resolvedBackupPath)
        $backupList = $backupDirectory.SearchBackups($groupPolicyManager.CreateSearchCriteria())
        
        foreach ($policyBackup in $backupList)
        {
            $migrationTable.Add(0, $policyBackup)
            $migrationTable.Add($constants.ProcessSecurity, $policyBackup)
        }
        #endregion Preparing basic migration table
        
        #region Applying identity and UNC mappings
        foreach ($entry in $migrationTable.GetEntries())
        {
            switch ($entry.EntryType)
            {
                $constants.EntryTypeUNCPath
                {
                    if ($entry.Source -like "\\$sourceDomainDNS\*")
                    {
                        $null = $migrationTable.UpdateDestination($entry.Source, $entry.Source.Replace("\\$sourceDomainDNS\", "\\$destDomainDNS\"))
                    }
                    if ($entry.Source -like "\\$sourceDomainNetBios\*")
                    {
                        $null = $migrationTable.UpdateDestination($entry.Source, $entry.Source.Replace("\\$sourceDomainNetBios\", "\\$destDomainNetBios\"))
                    }
                }
                
                { $constants.EntryTypeUser, $constants.EntryTypeGlobalGroup, $constants.EntryTypeUniversalGroup, $constants.EntryTypeUnknown -contains $_ } {
                    if ($mapping = $explicitIdentityMappings | Where-Object Source -EQ $entry.Source)
                    {
                        $null = $migrationTable.UpdateDestination($entry.Source, $mapping.Target)
                    }
                }
            }
        }
        
        # Additionally scan backup for share mappings, as those won't be found by default
        foreach ($gpoFolder in (Get-ChildItem -Path $resolvedBackupPath -Directory | Where-Object Name -Match '^(\{{0,1}([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}\}{0,1})$'))
        {
            $driveXmlPath = Join-Path -Path $gpoFolder.FullName -ChildPath 'DomainSysvol\GPO\User\Preferences\Drives\Drives.xml'
            if (-not (Test-Path -Path $driveXmlPath)) { continue }
            
            try { $driveXmlData = [xml](Get-Content -Path $driveXmlPath) }
            catch { continue }
            
            foreach ($driveSet in $driveXmlData.Drives.Drive)
            {
                if ($driveSet.Properties.Path -like "\\$sourceDomainDNS\*")
                {
                    $null = $migrationTable.AddEntry($driveSet.Properties.Path, $constants.EntryTypeUNCPath, $driveSet.Properties.Path.Replace("\\$sourceDomainDNS\", "\\$destDomainDNS\"))
                }
                if ($driveSet.Properties.Path -like "\\$sourceDomainNetBios\*")
                {
                    $null = $migrationTable.AddEntry($driveSet.Properties.Path, $constants.EntryTypeUNCPath, $driveSet.Properties.Path.Replace("\\$sourceDomainNetBios\", "\\$destDomainNetBios\"))
                }
            }
        }
        
        #endregion Applying identity and UNC mappings
        
        $migrationTable.Save($writePath)
        $writePath
    }
}