robocopy script

Below are three Robocopy command-line (CMD) scripts and three PowerShell scripts designed to automate daily system tasks, such as backups, folder synchronization, and log management. Each script includes practical use cases, clear comments, and is wrapped in an appropriate ““` tag with unique artifact IDs.


Robocopy CMD Scripts

CMD Script 1: Daily Backup of Documents to External Drive

This script backs up a user’s Documents folder to an external drive, including all file attributes and logging the operation.

@echo off
:: Script to back up Documents folder to an external drive daily
set SOURCE=C:\Users\%USERNAME%\Documents
set DEST=E:\Backups\Documents
set LOG=C:\Logs\Documents_Backup_%DATE:~-4%%DATE:~4,2%%DATE:~7,2%.txt

:: Create log directory if it doesn't exist
if not exist "C:\Logs" mkdir C:\Logs

:: Run Robocopy to copy files with attributes and log results
robocopy "%SOURCE%" "%DEST%" /MIR /COPYALL /R:3 /W:5 /LOG:"%LOG%"

:: Check if Robocopy was successful
if %ERRORLEVEL% leq 1 (
    echo Backup completed successfully. Log saved to %LOG%
) else (
    echo Backup failed. Check log at %LOG% for details.
)
pause


@echo off
:: Script to back up Documents folder to an external drive daily
set SOURCE=C:\Users\%USERNAME%\Documents
set DEST=E:\Backups\Documents
set LOG=C:\Logs\Documents_Backup_%DATE:~-4%%DATE:~4,2%%DATE:~7,2%.txt

:: Create log directory if it doesn’t exist
if not exist “C:\Logs” mkdir C:\Logs

:: Run Robocopy to copy files with attributes and log results
robocopy “%SOURCE%” “%DEST%” /MIR /COPYALL /R:3 /W:5 /LOG:”%LOG%”

:: Check if Robocopy was successful
if %ERRORLEVEL% leq 1 (
echo Backup completed successfully. Log saved to %LOG%
) else (
echo Backup failed. Check log at %LOG% for details.
)
pause

@echo off
:: Script to back up Documents folder to an external drive daily
set SOURCE=C:\Users\%USERNAME%\Documents
set DEST=E:\Backups\Documents
set LOG=C:\Logs\Documents_Backup_%DATE:~-4%%DATE:~4,2%%DATE:~7,2%.txt

:: Create log directory if it doesn’t exist
if not exist “C:\Logs” mkdir C:\Logs

:: Run Robocopy to copy files with attributes and log results
robocopy “%SOURCE%” “%DEST%” /MIR /COPYALL /R:3 /W:5 /LOG:”%LOG%”

:: Check if Robocopy was successful
if %ERRORLEVEL% leq 1 (
echo Backup completed successfully. Log saved to %LOG%
) else (
echo Backup failed. Check log at %LOG% for details.
)
pause

Use Case: Automates daily backups of the Documents folder to an external drive (E:), mirroring the source and logging the operation with a timestamped log file.


CMD Script 2: Sync Project Files to Network Share

This script synchronizes a project folder to a network share, excluding temporary files and using multi-threading for faster copying.

@echo off
:: Script to sync project files to a network share
set SOURCE=C:\Projects
set DEST=\Server\Share\Projects
set LOG=C:\Logs\Project_Sync_%DATE:~-4%%DATE:~4,2%%DATE:~7,2%.txt

:: Create log directory if it doesn’t exist
if not exist “C:\Logs” mkdir C:\Logs

:: Run Robocopy to sync files, excluding temp files, with multi-threading
robocopy “%SOURCE%” “%DEST%” /MIR /XF “.tmp” “.log” /MT:16 /R:3 /W:5 /LOG:”%LOG%”

:: Check if Robocopy was successful
if %ERRORLEVEL% leq 1 (
echo Sync completed successfully. Log saved to %LOG%
) else (
echo Sync failed. Check log at %LOG% for details.
)
pause

Use Case: Synchronizes a local Projects folder with a network share, excluding temporary files, and uses multi-threading to optimize performance.


CMD Script 3: Archive Old Logs to Backup Folder

This script archives log files older than 7 days to a backup folder, preserving file attributes.

@echo off
:: Script to archive log files older than 7 days
set SOURCE=C:\Logs
set DEST=E:\Archives\Logs
set LOG=C:\Logs\Archive_Log_%DATE:~-4%%DATE:~4,2%%DATE:~7,2%.txt

:: Create log and destination directories if they don’t exist
if not exist “C:\Logs” mkdir C:\Logs
if not exist “%DEST%” mkdir “%DEST%”

:: Run Robocopy to move files older than 7 days
robocopy “%SOURCE%” “%DEST%” *.log /MOV /MINAGE:7 /COPYALL /R:3 /W:5 /LOG:”%LOG%”

:: Check if Robocopy was successful
if %ERRORLEVEL% leq 1 (
echo Archive completed successfully. Log saved to %LOG%
) else (
echo Archive failed. Check log at %LOG% for details.
)
pause

Use Case: Moves log files older than 7 days from a source folder to an archive folder, preserving attributes and logging the operation.


Robocopy PowerShell Scripts

PowerShell Script 1: Daily Backup with Email Notification

This script backs up a folder, logs the operation, and sends an email notification upon completion.

PowerShell script to back up a folder and send email notification

$Source = “C:\Users\$env:USERNAME\Documents”
$Dest = “E:\Backups\Documents”
$LogDir = “C:\Logs”
$LogFile = “$LogDir\Documents_Backup_$(Get-Date -Format ‘yyyyMMdd’).txt”
$EmailTo = “[email protected]
$EmailFrom = “[email protected]
$SmtpServer = “smtp.example.com”

Create log directory if it doesn’t exist

if (-not (Test-Path $LogDir)) { New-Item -Path $LogDir -ItemType Directory }

Run Robocopy

robocopy $Source $Dest /MIR /COPYALL /R:3 /W:5 /LOG:$LogFile

Check Robocopy exit code

if ($LASTEXITCODE -le 1) {
$Subject = “Backup Success – $(Get-Date -Format ‘yyyy-MM-dd’)”
$Body = “Backup of $Source to $Dest completed successfully. Log: $LogFile”
} else {
$Subject = “Backup Failed – $(Get-Date -Format ‘yyyy-MM-dd’)”
$Body = “Backup of $Source to $Dest failed. Check log: $LogFile”
}

Send email notification

Send-MailMessage -To $EmailTo -From $EmailFrom -Subject $Subject -Body $Body -SmtpServer $SmtpServer

Write-Host $Body

Use Case: Backs up the Documents folder daily, logs the operation, and sends an email notification to an administrator with the status. (Note: Update $SmtpServer, $EmailTo, and $EmailFrom with actual values.)


PowerShell Script 2: Sync Files with Monitoring

This script synchronizes a folder and monitors for changes, automatically re-running the sync when changes are detected.

PowerShell script to sync a folder and monitor for changes

$Source = “C:\Data”
$Dest = “D:\Data_Backup”
$LogDir = “C:\Logs”
$LogFile = “$LogDir\Data_Sync_$(Get-Date -Format ‘yyyyMMdd’).txt”

Create log directory if it doesn’t exist

if (-not (Test-Path $LogDir)) { New-Item -Path $LogDir -ItemType Directory }

Run Robocopy with monitoring

robocopy $Source $Dest /MIR /MON:1 /R:3 /W:5 /LOG:$LogFile

Check Robocopy exit code

if ($LASTEXITCODE -le 1) {
Write-Host “Sync completed successfully. Log saved to $LogFile”
} else {
Write-Host “Sync failed. Check log at $LogFile for details.”
}

Use Case: Continuously monitors a source folder and synchronizes changes to a backup folder whenever a single change is detected, useful for real-time data syncing.


PowerShell Script 3: Clean and Backup Temporary Files

This script copies temporary files to a backup location and deletes them from the source if older than 30 days.

PowerShell script to back up and clean temporary files older than 30 days

$Source = “C:\Temp”
$Dest = “E:\Archives\Temp”
$LogDir = “C:\Logs”
$LogFile = “$LogDir\Temp_Cleanup_$(Get-Date -Format ‘yyyyMMdd’).txt”

Create directories if they don’t exist

if (-not (Test-Path $LogDir)) { New-Item -Path $LogDir -ItemType Directory }
if (-not (Test-Path $Dest)) { New-Item -Path $Dest -ItemType Directory }

Run Robocopy to copy and move files older than 30 days

robocopy $Source $Dest /MOV /MINAGE:30 /COPYALL /R:3 /W:5 /LOG:$LogFile

Check Robocopy exit code

if ($LASTEXITCODE -le 1) {
Write-Host “Temp files archived and cleaned successfully. Log saved to $LogFile”
} else {
Write-Host “Operation failed. Check log at $LogFile for details.”
}

Use Case: Archives temporary files older than 30 days to a backup location and removes them from the source to free up space.


How to Use These Scripts

  1. CMD Scripts:
  • Save each .cmd file to a location like C:\Scripts.
  • Schedule them using Windows Task Scheduler to run daily (e.g., at 2 AM).
  • Ensure the destination drives (e.g., E:) and network shares are accessible.
  • Run with administrative privileges for operations requiring permissions.
  1. PowerShell Scripts:
  • Save each .ps1 file to a location like C:\Scripts.
  • Set PowerShell execution policy if needed: Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned.
  • Schedule using Task Scheduler with a PowerShell action (e.g., powershell -File "C:\Scripts\script.ps1").
  • For the email script, configure valid SMTP server and email addresses.
  1. General Tips:
  • Test scripts with the /L option in Robocopy to simulate without making changes.
  • Ensure log directories exist or are created by the script.
  • Adjust paths (SOURCE, DEST, LOG) to match your environment.

These scripts provide a solid foundation for automating daily file management tasks with Robocopy, suitable for backups, synchronization, and cleanup.

FacebookTwitterEmailShare

Leave a Comment

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