MECM AfterBackup.bat

Managed ad

By justin, 22 November, 2022

The MECM AfterBackup.bat script gives you a method of running commands and scripts after the Backup Site Server maintenance task has finished. This can allow you to do some clean up and in the case of this example, compress it and move it to an achieve location. Here is a AfterBackup.bat file that runs a PowerShell script that is also in the “<ConfigMgrInstallationFolder>\Inboxes\Smsbkup.box” folder.

AfterBackup.bat example

Powershell.exe -executionpolicy bypass -File "%~dp0AfterBackup.ps1" -BackupPath "\\ithfs02\dist\Backup\ConfigMgr\P01Backup" -CopiesToKeep 7 -ZipDestination "\\ithfs02\dist\Backup\ConfigMgr\Zips" -SiteCode P01 -LogPath "D:\Program Files\Microsoft Configuration Manager\Logs"

The AfterBackup.bat file has called the AfterBackup.ps1 that is in the same folder as it is in.

AfterBackup.ps1 example

Param(
    $CopiesToKeep=7,
    $BackupPath,
    $ZipDestination,
    $SiteCode,
    $LogPath="D:\Program Files\Microsoft Configuration Manager\Logs"
)

Start-Transcript -Path "$LogPath\SMSBackupAfterBackup.log" -Force

$TimeStamp=((Get-Date -Verbose).tostring("yyyy.dd.MM.HH.mm.ss") )

Compress-Archive -Path "$BackupPath\*.*" -DestinationPath "$ZipDestination\$SiteCode.$TimeStamp.zip" -Verbose -Force -CompressionLevel Optimal

$Keep=Get-ChildItem .\*.zip | Sort LastWriteTime | Select -last $CopiesToKeep

 

$Files=Get-ChildItem .\*.zip | Sort LastWriteTime

foreach($file in $Files){

    if($file.FullName -in $Keep.fullname){

        Write-Host -Verbose "Keep $($file.fullname)" -ForegroundColor Green

 

 

    }else{

        Write-Host -Verbose "Delete $($file.fullname)" -ForegroundColor Red

        $File | Remove-Item -Force -Verbose

    }

}

Stop-Transcript

 

Looking in the AfterBackup.ps1, you will see it has several parameters that were used, including the path to save a log file called “SMSBackupAfterBackup.log” that it will save the Transcript of what happened when it ran. The script compresses the backup into a zip file and saves it as <SiteCode>.yyyy.MM.dd.HH.mm.ss.zip and only keeps the latest 7 zip files based on the LastWriteTime date/time.

Comments