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 https://sysadminben.wordpress.com $limit = (Get-Date).AddDays(-15) $SourcePath = "c:\folder" $TargetPath = "\\backupnas\Backup\servername" $SMTPRecipients = "user1@email.com","user2@email.com" $SMTPFrom = "smtp@email.com" $SMTPServer = "smtp.domain.com" $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

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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