This article is about a simple file backup script for home or small offices users to periodically backup the files in the computer or laptop to a shared folder/NAS or cloud drive.

Robocopy (Built-in tool in windows) is used to perform file copy and the power of PowerShell is used to manage the logs for monitoring the backup.

PowerShell Script:

#IMPORTANT : The folder path should be without "\" in the end.
#Destination path can be a local path or share path

$sourcePath = "D:\Data\Source"
$destinationPath = "\\networkShare\destination"
$logFolder = "C:\Logs"

#Number of log files that should be retained
$MAX_LOGFILE_COUNT = 6

#Fetching the username from the source computer so that a folder is created in the destination in the name of the user
$username = $env:USERNAME
$destinationPath += "\" + $username
$datestring = ((Get-Date).DateTime.ToString()).Replace(", ","_").Replace(" ","_").Replace(":"," ")
$logFilePath = $logFolder + "\log_$datestring.txt"
robocopy "$sourcePath" "$destinationPath" *.* /E /COPYALL /EFSRAW /SEC > $logFilePath
$files = Get-ChildItem -Path "$logFolder\log*.txt" | Sort-Object LastWriteTime -Descending

#To delete the log files if the number is more than the MAX value
$filecount = $files.Count
if($filecount -gt $MAX_LOGFILE_COUNT)
{
    $files[$MAX_LOGFILE_COUNT..$filecount] | %{ Remove-Item $_.FullName -Force -Recurse}
}

#To append ERROR to the name of the log file, of the code encounter any errors
$latestLogFilePath = (Get-ChildItem -Path $logFolder -File  | Sort-Object LastWriteTime -Descending)[0].FullName
$logContent = Get-Content -Path $latestLogFilePath
foreach($lines in $logContent) 
{
    if($lines -match "ERROR") 
    {
        #Alert mechanism or other logging codes can be added here
        Rename-Item -Path $latestLogFilePath -NewName $latestLogFilePath.Replace(".txt", "_ERROR_.txt")
        break
    }
}

Log Files:

The script can be saved to a .ps1 file and scheduled in the “Task Scheduler”.

Note: Required parameters are given to robocopy to retain the files in the destination even if the files are deleted from the source. By this it is easy to restore the same from the destination. But this affects real deletion process also. To resolve this, a mirror replication can be performed once a month to delete all unwanted data.

Every time the above script is executed, the modified files are copied from the source to the destination and a log file containing robocopy output is generated. The log files are automatically deleted when the number exceeds the set limit. Also if the file copy encounters any error, the respective log file’s name is appended with “_ERROR_” for easy identification and the log file content will have the error details.

To improve the copying mechanism, other parameters of robocopy such as restartable mode, backup mode etc. can be used.

Thank you for reading this article. Hope this is helpful to you.