[Batch] Backing Up Data with a Batch(.bat) File

本文最後更新於:2024年7月7日 晚上

The Need for Data Backup in Windows

Creating a batch file to automate the process of copying files to a specified directory on a regular schedule can be incredibly convenient. Here is a simple guide on using the xcopy command to achieve this.

Guide

1. Create Batch File

  1. backup.bat
    @ECHO OFF
    
    @REM Set language encoding to UTF-8
    chcp 65001
    
    IF "%1" == "" (
        SET /P source="Please enter the absolute path of the folder to be backed up: "
    ) ELSE (
        SET source=%~1
    )
    
    IF NOT EXIST "%source%\" (
        ECHO Path does not exist
        PAUSE
        EXIT
    )
    
    IF "%2" == "" (
        SET /P target="Please enter the absolute path for storing the backup: "
    ) ELSE (
        SET target=%~2
    )
    
    IF EXIST "%target%\" (
        choice /c Yn /m "The target path already contains files. Do you want to overwrite?"
    
        @REM Incorrect condition
        IF ERRORLEVEL 255 GOTO CLOSE
        @REM Choose not to overwrite
        IF ERRORLEVEL 2 GOTO CLOSE
        @REM Choose to continue backup
        IF ERRORLEVEL 1 GOTO CONTINUE
    
        @REM Cancel command
        IF ERRORLEVEL 0 GOTO CLOSE
    
        :CLOSE
            ECHO Backup canceled
            PAUSE
            EXIT
    
        :CONTINUE
            ECHO The target path files will be overwritten
            PAUSE
    )
    
    xcopy "%source%" "%target%" /s /e /h /i /c /y
    
    ECHO File backup complete
    
    PAUSE
    Please note that the encoding format of this batch file should be saved as UTF-8 or you can save it in another encoding and modify the chcp setting accordingly to avoid any issues with garbled Chinese characters.

2. Usage

  1. Directly input the source and target directories in the command:

    backup.bat "C:\test\source" "C:\test\target"
  2. Double-click the file to use the interactive command line to input the target directory:
    image.png

Environment

  • Windows 10

References


[Batch] Backing Up Data with a Batch(.bat) File
https://hankz1108.github.io/posts/20240707-en-20231107-batch-backup-folder/
作者
Hankz
發布於
2024年7月7日
更新於
2024年7月7日
許可協議