Friday, September 6, 2019

PowerShell Script for Group Policy backup

This script allows you to create a task to reserve group policies of your Active Directory domain in case of changes or their accidental removal:

$Path = "D:\GP_Backup\"
$Days = "30"
$date = Get-Date -format yyyyMMdd
New-Item -Path $Path\$date -ItemType "directory"
Backup-GPO -All -Path $Path\$date
&$env:ProgramFiles\WinRar\rar a -r $Path\$date $Path\$date
Remove-Item $Path\$date -Recurse -Force
$Now = Get-Date
$LastWrite = $Now.AddDays(-$Days)
$Files = Get-Childitem $Path -Recurse | Where {$_.LastWriteTime -le "$LastWrite"}
Foreach ($File in $Files)
    {
    If ($File -ne $NULL)
        {
        Remove-Item $File.FullName | Out-Null
        }
    }


where  $Path - the directory for storing backups;
           $Days - all copies created earlier than this number of days ago will be deleted.

Each time the script is triggered, a backup copy of group policies will be created in the target folder with "yyyymmdd" format. Archiving is done by an external program WinRar, that must be installed in advance.

No comments:

Post a Comment