Copies the settings in a GPO to another GPO

 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
###########################################################################
# Function : CopyGpo
# Description: Copies the settings in a GPO to another GPO
# Parameters : $sourceGpo - The GPO name or GPO ID of the GPO to copy
# : $sourceDomain - The dns name, such as microsoft.com, ofthedomain where the original GPO is located
# : $targetGpo - The GPO name of the GPO to add
# : $targetDomain - The dns name, such as microsoft.com, of the domain where the copy should be put
# : $migrationTable - The path to an optional Migration table to use when copying the GPO
# Returns : N/A
# Dependencies: Uses GetGpoByNameOrID, found in article download
###########################################################################
function copy-gpo(
  [string] $sourceGpo = $(throw '$sourceGpo is required'),
  [string] $sourceDomain = $(throw '$sourceDomain is required'),
  [string] $targetGpo = $(throw '$targetGpo is required'),
  [string] $targetDomain = $(throw '$targetDomain is required'),
  [string] $migrationTable = $(''),
[switch] $copyAcl)
{
  $gpm = New-Object -ComObject GPMgmt.GPM # Create the GPMC Main object
  $gpmConstants = $gpm.GetConstants() # Load the GPMC constants
  $gpmSourceDomain = $gpm.GetDomain($sourceDomain, '', $gpmConstants.UseAnyDC) # Connect to the domain passed

  # using any DC
  $gpmSourceGpo = GetGpoByNameOrID $sourceGpo $gpmSourceDomain

  # Handle situations where no or multiple GPOs was found
  switch ($gpmSourceGpo.Count)
  {
    {
      $_ -eq 0
    } 
    {
      throw 'No GPO named $gpoName found'
      return
    }
    {
      $_ -gt 1
    } 
    {
      throw 'More than one GPO named $gpoName found'
      return
    }
  }

  if ($migrationTable)
  {
    $gpmMigrationTable = $gpm.GetMigrationTable($migrationTable)
  }
  $gpmTargetDomain = $gpm.GetDomain($targetDomain, '', $gpmConstants.UseAnyDC) # Connect to the domain passed

  # using any DC
  $copyFlags = 0
  if ($copyAcl)
  {
    $copyFlags = Constants.ProcessSecurity
  }

  $gpmResult = $gpmSourceGpo.CopyTo($copyFlags, $gpmTargetDomain, $targetGpo)
  [void] $gpmResult.OverallStatus
}