Powershell script to backup GPO

This article contains Powershell script which will backup Active Directory Group Policy Objects.

<#Description:
This script will create folder for each start of this script
and perform backup of GPO's in actual domain joined computer.
Then will remove old backups specified in variable below.
#>

#-----User variables to modify-----#
$Path = "C:\Backups\GPO-Backup" #Destination backup folder
$Days = "30" #How many days to keep in backup $Path folder
#----------------------------------#

#--Execution code (do not touch)---#
$ActualDate = (Get-Date -Format d.M.yyyy__H_mm_s) #Actual date for folder creation
$sw = [system.diagnostics.stopwatch]::startNew()

If ((Test-Path -Path $Path)) {
    If (Get-Module -ListAvailable -Name GroupPolicy) {
        $sw.Start()
        Import-Module GroupPolicy -ErrorAction Stop
        New-Item -Path "$Path\$ActualDate" -ItemType directory
        Start-Transcript -Path "$Path\$ActualDate\TranscriptLog.txt" #To Keep GpoId and Id history to better identify GPOs
        Backup-GPO -All -Path "$Path\$ActualDate"
        $DeleteFolders = (Get-ChildItem -Path $Path | Where-Object PSIsContainer -eq "True" | Where-Object CreationTime -le (Get-Date).AddDays(-$Days) ) | Remove-Item -Force -Recurse
        $sw.Stop()
        Write-Output "Finished! Removed backup GPO folders based on '$Days' days retention period. Elapsed time: $($sw.Elapsed.Seconds) seconds."
        Stop-Transcript
    }#EndIf
    
    Else {
        Write-Warning "Script stopped! GroupPolicy module is not installed on this machine!"
    }#EndElse

}#EndIf
Else {
    Write-Warning "Script stopped! Provided path '$Path' does not exist!"
}#EndElse
#----------------------------------#

 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.