热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

ThreeStepstoMigrateGroupPolicyBetweenActiveDirectoryDomainsorForestsUsingPowerShell

Haveyoueverwishedthatyouhadthreelegs?Imaginehowmuchfasteryoucouldrun.Todaywearegoingtolook

Three Steps Ahead

Have you ever wished that you had three legs? Imagine how much faster you could run.  Today we are going to look at three steps to migrating GPOs between domains or forests with PowerShell.  Now that is fast!

The Problem

Have you ever wanted to copy all of your production Group Policy Objects (GPOs) into a lab for testing?  Do you have to copy GPOs between domains or forests?  Do you need to migrate them to another environment due to an acquisition, merger, or divestiture? These are common problems for many administrators.

There are Vbscripts provided with the Group Policy Management Console (GPMC), but that is so "last decade". (Really. They were published in 2002.)  What about WMI filters, OU links, login scripts, and embedded credentials? I’ve drafted a PowerShell module to do this with speed and style. This post discusses the pitfalls, preparations, and scripts for a successful GPO migration.

Real-World Scenario

Recently I worked with a customer who had mirrored dev, test, and prod Active Directory forests.  They had the same accounts, groups, OUs, and GPOs in all three places.  Then they had another version of the same dev, test, prod environment for a separate application.  That is two sets of three forests, both with identical GPOs.  Their current process for copying policies was manually backing up and importing the GPOs, which is how TechNet tells you to do it.  At this scale, however, they were in need of an automated solution.  Enter PowerShell.

Scripting Options

When automating Group Policy with the tools in the box you have three options:

  1. Group Policy Management Console (GPMC) Vbscripts (circa 2002)
  2. GroupPolicy PowerShell module (Windows Server 2008 R2 and above, installed with GPMC)
  3. GPMgmt.GPM COM object which is the secret sauce behind #1 and #2

Vbscript.  Yeah.  That worked great all those years ago.  I know.  That’s what I used day-in-day-out before PowerShell.  But this is a new era.  If you are still relying on Vbscript, then it is time for an intervention from your peers.

My default choice is always to use the cmdlets out-of-the-box.  And that it what I tried to do for the most part.  However, while developing this solution I ran into a number of limitations with the GroupPolicy module cmdlets.  I’ll detail those below.

Behind the Vbscripts and the cmdlets there is a COM object called “GPMgmt.GPM”.  Here is a list of the methods exposed by the object:

PS C:\> New-Object -ComObject GPMgmt.GPM | Get-Member | Select-Object Name

Name 
---- 
CreateMigrationTable 
CreatePermission 
CreateSearchCriteria 
CreateTrustee 
GetBackupDir 
GetBackupDirEx 
GetClientSideExtensions 
GetConstants 
GetDomain 
GetMigrationTable 
GetRSOP 
GetSitesContainer 
InitializeReporting 
InitializeReportingEx

For example, the Get-GPResultantSetOfPolicy cmdlets calls the GetRSOP method of this COM object.  However, we do not have full cmdlet coverage.  There are no cmdlets for working with GPO migration tables.  Therefore I studied the migration table Vbscripts and essentially converted them to PowerShell.  The Vbscripts have great value as templates for how to use this COM object.  It’s just not cool to rely on Vbscript for much else these days.

GPO Scripting Challenges

When I first sat down to tackle GPO migration I found the convenient cmdlet Copy-GPO.  Game over, right?  Just use the cmdlet.  Oh, how I wish it were that easy.  To make a very long story very short here is a summary of the challenges I encountered:

  • Copy-GPO requires both source and destination domains to be online.  That means we cannot use it for disconnected dev, test, prod forest scenarios.  No problem.  I’ll just use Backup-GPO and Import-GPO…
  • Backup-GPO/Import-GPO does not have the -CopyACL switch from Copy-GPO.  Now I have to find another way to migrate permissions.  No problem.  I’ll just use the Get-GPPermission/Set-GPPermission cmdlets…
  • Set-GPPermission will not set deny entries, only allow.  Seriously?  Some shops rely on deny.  I had to write my own code for this piece, and it was quite involved.  However, I used the opportunity to translate permissions based on the migration table, so that made it more robust in the end.
  • 技术分享As mentioned above there are no cmdlets for Group Policy Migration Tables.  This is a necessary evil for most GPO migrations.  Restricted groups, user rights assignment, script paths, etc. can be buried down in the policies. Migration tables tell the import how to translate accounts and paths in policies to the new domain.  Usually creating a migration table is a manual process with an ancient GUI tool.  I automated the whole thing using a simple CSV file where you can specify search/replace values to automatically update the automatically generated migration table.
  • Import-GPO has a parameter to use a migration table, but it forces the option from the GUI which requires all accounts to be in the migration table.  I left this one as-is.  You can work around this by adjusting the migration table or fudging accounts.
  • Neither Copy-GPO nor Import-GPO support WMI filter migration.  After extensive research I discovered that WMI filter scripting may require a registry hack and a DC reboot due to a “system owned object” feature.  This one is the ugliest of them all, and I decided to leave it alone.  Bin Yi from Microsoft has posted a PowerShell module on the TechNet Script Gallery for migrating WMI filters.  Feel free to use his code if you need this functionality.  Backup-GPO puts all the WMI filter data into the backup, but writing it back to the new environment is the challenge.  I’ll tackle this later if I have demand for it.

In this case the old saying is true, “It is never as easy as it looks.”

The Process

If there ever were a case for automation this is it.  The export process allows us to do multiple GPOs simultaneously, and some of the import steps are optional.  Even so, it is quite involved.  Here is the complete, manual GPO migration process:

  1. Export GPOs from source domain
  2. Copy export files to destination domain
  3. Create and tweak migration table
  4. Manually recreate WMI filters in destination
  5. Remove GPOs of same name in destination
  6. Import GPOs to destination domain
  7. Manually reassign WMI filters
  8. Copy permissions (and sync SYSVOL permissions)
  9. Link GPOs to OUs
  10. Set link properties (enabled, enforced, etc.)

Now imagine repeating that effort… multiple times… by hand… without making any mistakes… without forgetting a step… and keeping your sanity.

Beginner Tip:  If you have never done a GPO backup and import from the GUI, then I suggest you start there first.  That will give you a better idea of the overall process.  You will want to click the option for the migration table so that you understand it as well.

The Solution

My mission is to make things simple for Microsoft customers.  I was able to reduce the entire manual process down to a new PowerShell module and a CSV file.  Here is an outline of the new module cmdlets involved.  You will notice these correlate directly to the process steps above (except for WMI not supported in this release).

  • Start-GPOExport
    • Invoke-BackupGPO
      • (Backup-GPO)
      • Export-GPPermission
  • Start-GPOImport
    • New-GPOMigrationTable
    • Show-GPOMigrationTable
    • Test-GPOMigrationTable
    • Invoke-RemoveGPO
      • (Remove-GPO)
    • Invoke-ImportGPO
      • (Import-GPO)
      • Import-GPPermission
    • Import-GPLink

Let‘s break this down into three steps, well four if you count the setup, or maybe five if you count extra tinkering.

Step 0 – Setup

In the source domain and destination domain you want a workstation or member server with the following basic requirements:

  • PowerShell version 2 or above
  • Remote Server Administration Tools (RSAT)
    • Active Directory module
    • Group Policy module
    • GPMC

On your machine set up a working folder where you copy the PowerShell files from this blog post.  The download link is at the bottom of the article.  By the way, you will usually need to unblock the file(s) after download.

I developed this on a Windows 8.1 client running PowerShell v4 and tested it on Windows Server 2008 R2 (PSv2), Windows Server 2012 (PSv3), and Windows Server 2012 R2 (PSv4).

Step 1 – Migration Table CSV File

We will call this the “migration table CSV file”.  It is not a GPO  migration table, but it feeds the automation process behind building and updating the migration table.  Before we run the migration code we need to create a simple CSV file that maps source domain references to the destination domain.  Here is an example that is included with the code:

Source               Destination         Type
------               -----------         ----
wingtiptoys.local    cohovineyard.com    Domain
wingtiptoys          cohovineyard        Domain
\\wingtiptoys.local\ \\cohovineyard.com\ UNC
\\wingtiptoys\       \\cohovineyard\     UNC

Notice there are short name (NetBIOS) and long name (FQDN) entries for each domain and for both “Domain” and “UNC” type.  You can add other values for server names in UNC paths, etc.  This is my suggested minimum.  You will want one of these files for each combination of source/destination domains where you are migrating GPOs.  Make copies of the sample and modify them to your needs.

Step 2 – Export

The ZIP download includes a sample calling script for the export.  All you have to do is update the working folder path, modify the domain and server names, and then edit the Where-Object line to query the GPO(s) you want to migrate.

Set-Location "C:\Temp\GPOMigration\"            
            
Import-Module GroupPolicy            
Import-Module ActiveDirectory            
Import-Module ".\GPOMigration.psm1" -Force            
            
# This path must be absolute, not relative            
$Path        = $PWD  # Current folder specified in Set-Location above            
$SrceDomain  = ‘wingtiptoys.local‘            
$SrceServer  = ‘dca.wingtiptoys.local‘            
$DisplayName = Get-GPO -All -Domain $SrceDomain -Server $SrceServer |            
    Where-Object {$_.DisplayName -like ‘*test*‘} |             
    Select-Object -ExpandProperty DisplayName            
            
Start-GPOExport `
    -SrceDomain $SrceDomain `
    -SrceServer $SrceServer `
    -DisplayName $DisplayName `
    -Path $Path            

Run the script.  This calls the necessary module functions to create the GPO backup and export the permissions.  Note that the permissions are listed in the GPO backup, but there is no practical way to decipher them.  (Trust me.  Long story.)  In this case we’re going to dump the permissions to a simple CSV that gets written into the same GPO backup folder.

The working folder will now include a subfolder with the GPO backup.  Copy the entire working folder to your destination domain working machine.

Step 3 – Import

This is where most of the fancy foot work takes place, but I’ve reduced it to “one big button” if that meets your needs.  The ZIP download includes a sample calling script for the import.  This time you have to update the working folder path, modify the domain and server names, update the backup folder path, and then update the migration table CSV path to point to the file you created in Step 1 above.

Note:  Be sure not to confuse the source and destination domain/server names.  It would be unfortunate if you got those backwards when working in a production environment.  Just sayin’.  You’ve been warned.

Set-Location "C:\Temp\GPOMigration\"            
            
Import-Module GroupPolicy            
Import-Module ActiveDirectory            
Import-Module ".\GPOMigration.psm1" -Force            
            
# This path must be absolute, not relative            
$Path        = $PWD  # Current folder specified in Set-Location above            
$BackupPath  = "$PWD\GPO Backup wingtiptoys.local 2014-04-23-16-37-31"            
$DestDomain  = ‘cohovineyard.com‘            
$DestServer  = ‘cvdcr2.cohovineyard.com‘            
$MigTableCSVPath = ‘.\MigTable_sample.csv‘            
            
Start-GPOImport `
    -DestDomain $DestDomain `
    -DestServer $DestServer `
    -Path $Path `
    -BackupPath $BackupPath `
    -MigTableCSVPath $MigTableCSVPath `
    -CopyACL            

Run the script.  This calls the necessary module functions to import each GPO from the backup and put everything back in place in the destination domain.  After the script finishes review the output.  Check for any errors.  Verify the results in the destination domain using GPMC.  You can always rerun the script as many times as you like, making adjustments each time.

The working folder will now include a *.migtable file for the GPO migration table.  You can view and edit this, but be aware that the default logic in Start-GPOImport will create a new one each time.  Using Start-GPOImport requires to have the same accounts in the source and destination domains.  You can adjust the migration table and instead use Invoke-ImportGPO directly with your custom migration table.  Most likely the migration table will take some time to smooth out.  You’ll catch on.

Also be aware that by default Start-GPOImport removes any existing GPOs with the same name.  This is by design.  Remember that you can tweak the Start-GPOImport function to suit your own needs.

Step 4 – Free Style

Once you get the hang of the process I encourage you to dive into the Start-GPOImport function contained in the module.  It is pre-set to do a full import.  Your needs will likely vary from this template.  Use the syntax from this function to build your own import routine tailored to your requirements.

Summary

In a nut shell I’ve taken a multiple step manual process and condensed it down to three simple steps that execute quickly in PowerShell.  I agree that it is a pain to update paths in the calling script and copy files around.  On the bright side it is still way faster than the manual alternative.

As always when you are copying scripts from the internet make sure that you understand what the script will do before you run it.  Test it in a lab before using it in production.  Open up the GPOMigration.psm1 module file and skim through the code.  Review the full help content for each function.  You will learn more PowerShell and get ideas for your own scripts.

I’d love to hear how this script module has helped you.  Please use the comments below to ask questions and offer feedback.  Put your best foot forward with PowerShell!

Get the script here on the TechNet Script Center.

Read the follow up post with WMI filter migration supported.

Three Steps to Migrate Group Policy Between Active Directory Domains or Forests Using PowerShell


推荐阅读
  • 本文介绍了C#中数据集DataSet对象的使用及相关方法详解,包括DataSet对象的概述、与数据关系对象的互联、Rows集合和Columns集合的组成,以及DataSet对象常用的方法之一——Merge方法的使用。通过本文的阅读,读者可以了解到DataSet对象在C#中的重要性和使用方法。 ... [详细]
  • 本文介绍了lua语言中闭包的特性及其在模式匹配、日期处理、编译和模块化等方面的应用。lua中的闭包是严格遵循词法定界的第一类值,函数可以作为变量自由传递,也可以作为参数传递给其他函数。这些特性使得lua语言具有极大的灵活性,为程序开发带来了便利。 ... [详细]
  • 本文介绍了使用Java实现大数乘法的分治算法,包括输入数据的处理、普通大数乘法的结果和Karatsuba大数乘法的结果。通过改变long类型可以适应不同范围的大数乘法计算。 ... [详细]
  • HDU 2372 El Dorado(DP)的最长上升子序列长度求解方法
    本文介绍了解决HDU 2372 El Dorado问题的一种动态规划方法,通过循环k的方式求解最长上升子序列的长度。具体实现过程包括初始化dp数组、读取数列、计算最长上升子序列长度等步骤。 ... [详细]
  • 本文讨论了如何优化解决hdu 1003 java题目的动态规划方法,通过分析加法规则和最大和的性质,提出了一种优化的思路。具体方法是,当从1加到n为负时,即sum(1,n)sum(n,s),可以继续加法计算。同时,还考虑了两种特殊情况:都是负数的情况和有0的情况。最后,通过使用Scanner类来获取输入数据。 ... [详细]
  • 本文介绍了OC学习笔记中的@property和@synthesize,包括属性的定义和合成的使用方法。通过示例代码详细讲解了@property和@synthesize的作用和用法。 ... [详细]
  • 知识图谱——机器大脑中的知识库
    本文介绍了知识图谱在机器大脑中的应用,以及搜索引擎在知识图谱方面的发展。以谷歌知识图谱为例,说明了知识图谱的智能化特点。通过搜索引擎用户可以获取更加智能化的答案,如搜索关键词"Marie Curie",会得到居里夫人的详细信息以及与之相关的历史人物。知识图谱的出现引起了搜索引擎行业的变革,不仅美国的微软必应,中国的百度、搜狗等搜索引擎公司也纷纷推出了自己的知识图谱。 ... [详细]
  • 本文详细介绍了Linux中进程控制块PCBtask_struct结构体的结构和作用,包括进程状态、进程号、待处理信号、进程地址空间、调度标志、锁深度、基本时间片、调度策略以及内存管理信息等方面的内容。阅读本文可以更加深入地了解Linux进程管理的原理和机制。 ... [详细]
  • 1,关于死锁的理解死锁,我们可以简单的理解为是两个线程同时使用同一资源,两个线程又得不到相应的资源而造成永无相互等待的情况。 2,模拟死锁背景介绍:我们创建一个朋友 ... [详细]
  • 《数据结构》学习笔记3——串匹配算法性能评估
    本文主要讨论串匹配算法的性能评估,包括模式匹配、字符种类数量、算法复杂度等内容。通过借助C++中的头文件和库,可以实现对串的匹配操作。其中蛮力算法的复杂度为O(m*n),通过随机取出长度为m的子串作为模式P,在文本T中进行匹配,统计平均复杂度。对于成功和失败的匹配分别进行测试,分析其平均复杂度。详情请参考相关学习资源。 ... [详细]
  • 动态规划算法的基本步骤及最长递增子序列问题详解
    本文详细介绍了动态规划算法的基本步骤,包括划分阶段、选择状态、决策和状态转移方程,并以最长递增子序列问题为例进行了详细解析。动态规划算法的有效性依赖于问题本身所具有的最优子结构性质和子问题重叠性质。通过将子问题的解保存在一个表中,在以后尽可能多地利用这些子问题的解,从而提高算法的效率。 ... [详细]
  • 高质量SQL书写的30条建议
    本文提供了30条关于优化SQL的建议,包括避免使用select *,使用具体字段,以及使用limit 1等。这些建议是基于实际开发经验总结出来的,旨在帮助读者优化SQL查询。 ... [详细]
  • 本文介绍了指针的概念以及在函数调用时使用指针作为参数的情况。指针存放的是变量的地址,通过指针可以修改指针所指的变量的值。然而,如果想要修改指针的指向,就需要使用指针的引用。文章还通过一个简单的示例代码解释了指针的引用的使用方法,并思考了在修改指针的指向后,取指针的输出结果。 ... [详细]
  • 猜字母游戏
    猜字母游戏猜字母游戏——设计数据结构猜字母游戏——设计程序结构猜字母游戏——实现字母生成方法猜字母游戏——实现字母检测方法猜字母游戏——实现主方法1猜字母游戏——设计数据结构1.1 ... [详细]
  • CentOS 7部署KVM虚拟化环境之一架构介绍
    本文介绍了CentOS 7部署KVM虚拟化环境的架构,详细解释了虚拟化技术的概念和原理,包括全虚拟化和半虚拟化。同时介绍了虚拟机的概念和虚拟化软件的作用。 ... [详细]
author-avatar
手机用户2502923413
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有