PowerShell RoboCopy Wrapper
Sunday, August 21, 2011 at 12:00PM
Kieran Jacobsen in Coding, Windows, powershell

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:

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.

Article originally appeared on Aperture Science (http://kjacobsen.squarespace.com/).
See website for complete article licensing information.