Skip to content

Instantly share code, notes, and snippets.

Created April 22, 2014 06:51
Show Gist options
  • Save janikvonrotz/11167763 to your computer and use it in GitHub Desktop.
Save janikvonrotz/11167763 to your computer and use it in GitHub Desktop.
PowerShell: Backup Active Directory Group Policies#PowerShell#ActiveDirecoty
$Metadata = @{
Title = "Backup Active Directory Group Policies"
Filename = "Backup-ADGroupPolicies.ps1"
Description = ""
Tags = "backup, active, directory, group, object, policy"
Project = ""
Author = "Janik von Rotz"
AuthorContact = ""
CreateDate = "2014-04-22"
LastEditDate = "2014-04-22
Url = ""
Version = "0.0.0"
License = @'
This work is licensed under the Creative Commons Attribution-ShareAlike 3.0 Switzerland License.
To view a copy of this license, visit or
send a letter to Creative Commons, 444 Castro Street, Suite 900, Mountain View, California, 94041, USA.
# modules
Import-Module ActiveDirectory
Import-Module GroupPolicy
# settings
$Path = "C:\backup\GroupPolicy"
# main
# create backup file name
$Filename = "GroupPolicyFull" + "#" + $((Get-Date -Format s) -replace ":","-") + ".bak"
$Filepath = Join-Path $Path $Filename
# backup active directory
Get-GPO -All | ForEach-Object{
$GPOFilepath = Join-Path $Filepath $_.DisplayName
New-Item -Path $GPOFilepath -ItemType Directory
Backup-GPO -Guid $_.ID -Path $GPOFilepath
# get dates for backup retention exclusion
$Today = Get-Date -Format d
$FirstDateOfWeek = Get-Date (Get-Date).AddDays(-[int](Get-Date).Dayofweek) -Format d
$FirstDateOfMonth = Get-Date -Day 1 -Format d
# delete all backups except for today, first day of week and first day of month
Get-ChildItem $Path | select *,@{L="CreationTimeDate";E={Get-Date $_.CreationTime -Format d}} | Group-Object CreationTimeDate | %{
# only one backup per day
if($_.Count -gt 1){
$_.Group | Sort-Object CreationTime -Descending | Select-Object -Skip 1
# keep only required backups
$_.Group | Where-Object{$_.CreationTimeDate -ne $Today -and $_.CreationTimeDate -ne $FirstDateOfWeek -and $_.CreationTimeDate -ne $FirstDateOfMonth}
} | Remove-Item -Recurse -Force
Write-PPErrorEventLog -Source "Backup ActiveDirectory Group Policies" -ClearErrorVariable
<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="">
<Author>Janik von Rotz(</Author>
<Description>Backup ActiveDirectory Group Policies</Description>
<Actions Context="Author">
<Arguments>$(Get-ChildItem -Path $PSscripts.Path -Filter "Backup-ADGroupPolicies.ps1.ps1" -Recurse).Fullname</Arguments>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment