Posh Security

View Original

PowerShell RoboCopy Wrapper

So I find myself copying files from point A to point B on a regular basis, so much so, that I find myself using robocopy in a Windows scheduled task. The problem with this approach, is that there isn't many easy ways of working out if it worked, or worse, if something bad has happened!

I bashed out a script several years ago, and finally updated it to make use of the template that I posted up previous.

There are a few things to note with the script:

  • I always check if the source and destination exist, and report an error if they don't
  • My scripts always use the /MIR command, and limit retries to 3
  • Robocopy return codes:
    0: Completed sucessfully, but didn't copy any files
    1: Completed sucessfully and copied files
    rest: some error has occured

The bulk of the code is:

#robocopy task
$result = robocopy $source $destination /MIR /R:3

#robocopy sucess is:     0: no errors, but no copying done
#                        1: one or more files were copied sucessfully

#check there were no errors in the robo copy
if ($lastexitcode -gt 1)
{
    if ($lastexitcode -eq 0)
    {
        $messagebody = "Robocopy completed but no files copied! `n"
        foreach ($x in $result) {$messagebody = $messagebody + $x + "`n"}
        send-email $messagebody $false
    } elseif ($lastexitcode -eq 1)
    {
        #do nothing, it worked
    } else {
        $messagebody = "Robocopy returned an unknown error! `n"
        foreach ($x in $result) {$messagebody = $messagebody + $x + "`n"}
        send-email $messagebody $false
        exit 3
    }
}

The entire script is in the samples section, here.