Login Register






Thread Rating:
  • 0 Vote(s) - 0 Average


Advanced File Copy with Error Handling and Logging filter_list
Author
Message
Advanced File Copy with Error Handling and Logging #1
@echo off
setlocal enabledelayedexpansion

set sourceFile=example.txt
set destinationFolder=C:\Destination
set logFile=copy_log.txt

echo Copying %sourceFile% to %destinationFolder%...

copy %sourceFile% %destinationFolder% > nul 2>&1

if %errorlevel% neq 0 (
    echo Error: Unable to copy %sourceFile% to %destinationFolder%. >> %logFile%
    echo Date and Time: %date% %time% >> %logFile%
) else (
    echo Copy operation completed successfully. >> %logFile%
    echo Date and Time: %date% %time% >> %logFile%
)

endlocal

Explanation:

    setlocal enabledelayedexpansion: Enables delayed expansion of variables to handle changing variables within loops or code blocks.
    copy %sourceFile% %destinationFolder% > nul 2>&1: Copies the source file to the destination folder, redirecting both standard output and error output to null.
    if %errorlevel% neq 0: Checks the exit code of the copy command to determine if there was an error during the copy operation.
    If there was an error, it logs an error message along with the date and time to a log file (copy_log.txt).
    If the copy operation was successful, it logs a success message along with the date and time to the log file.

This example showcases error handling and logging, which are common in more advanced scripting scenarios. Keep in mind that if your scripting requirements become more complex, transitioning to a more feature-rich scripting language like PowerShell or a programming language like Python may be a more suitable choice.

Reply







Users browsing this thread: 1 Guest(s)