Checking if source and destination exist in robocopy script

PowerShell script that uses Robocopy to copy files, verify source and destination and then sends an email on completion.

Here is a basic PowerShell script to copy files also checking if the source and destination locations exist. PowerShell will then send an email if the Robocopy process completed successfully.

Example:

@echo off

set "source=C:\SourceFolder"
set "destination=\\RemoteServer\SharedFolder"
set "smtpServer=smtp.example.com"
set "sender=sender@example.com"
set "recipient=recipient@example.com"

REM Check if source folder exists
if not exist "%source%" (
    echo Source folder does not exist.
    exit /b
)

REM Check if destination folder exists
if not exist "%destination%" (
    echo Destination folder does not exist.
    exit /b
)

REM Check if destination is accessible
dir "%destination%" >nul 2>&1
if not %errorlevel%==0 (
    echo Destination folder is not accessible.
    exit /b
)

REM Perform the copy operation
robocopy "%source%" "%destination%" /E /COPYALL /R:3 /W:10 /MT

REM Check Robocopy exit code
if not %errorlevel%==0 (
    echo Robocopy encountered an error.
    exit /b
)

REM Send email notification
powershell.exe -ExecutionPolicy Bypass -Command "Send-MailMessage -From '%sender%' -To '%recipient%' -Subject 'Robocopy Complete' -Body 'Robocopy operation completed successfully.'"

exit /b

Let’s breakdown some of the variables in the script:

  • ‘source’: Path of the local source folder.
  • ‘destination’: Path of the remote destination folder.
  • ‘smtpserver’: SMTP server address for sending email.
  • ‘sender’: Email address of the sender.
  • ‘recipient’: Email address of the recipient.

So, after the Robocopy operation finishes, the script checks the Robocopy exit code, if the exit code is a success, the script will proceed to send and email using PowerShell ‘Send-EmailMessage’ cmdlet. Please feel free to customize it, you also might need to add variables for mail port and possible username and password of the email sender.

You will also need adjust the execution policy of PowerShell (‘Set-ExecutionPolicy Unrestricted’) if needed.