Simple Robocopy Backup Script

This simple backup script will copy a folder to another server using dated folders and delete old backup folders older than the specified number of days (15 in this example). Add this script to the task scheduler. In an AD environment, assign rights to the target location to the computer object and run the task as SYSTEM to avoid pesky service accounts.

# Written by Ben Penney $limit = (Get-Date).AddDays(-15) $SourcePath = "c:\folder" $TargetPath = "\\backupnas\Backup\servername" $SMTPRecipients = "","" $SMTPFrom = "" $SMTPServer = "" $SMTPSubject = "Server backup" $EmailBody = "Starting process $(Get-Date)`n" # Delete folders older than the $limit. Get-ChildItem -Path $path -Force | Where-Object { $_.PSIsContainer -and $_.CreationTime -lt $limit } | ForEach { $EmailBody += "Deleting folder "+($_.Name) Remove-Item -Force -recurse } $DateString = (Get-Date).ToString("yyyyMMdd") $RobocopyOutput = RoboCopy $SourcePath $TargetPath\$DateString /COPY:DAT /E /R:2 /W:2 /NFL /NDL /NP # OPTIONAL CODE TO TRUNCATE THE ROBOCOPY OUTPUT If ($RobocopyOutput.Count -gt 200) { $RobocopyOutput = $RobocopyOutput[0..200] $RobocopyOutput[0] = "********** ROBOCOPY LOG TRUNCATED ************" } $EmailBody += [system.string]::join("`n",$RobocopyOutput) If ($EmailBody.Contains("ERROR")) {$SMTPSubject += " ***ERRORS***"} $EmailBody += "`n`nFinished process $(Get-Date)" Send-MailMessage -To $SMTPRecipients -From $SMTPFrom -Subject $SMTPSubject -SMTPServer $SMTPServer -Body $EmailBody


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s