简体   繁体   中英

How do I exclude specific directories from a recursive copy in a Windows batch file?

I'm writing a shell script to backup the contents of the current directory to a timestamped subdirectory, ./STATES/$DATE . Obviously I do not want to STATES directory itself to be re-copied each time I backup the folder, so I need to somehow exclude it from the copy.

Here's an untested shell script showing how I'd approach this on *nix:

ID="$(date +%Y%b%d%H%M%S)"
COMMITABLE="$(ls | egrep --invert-match ^STATES\$)"
STATE_PATH="$(pwd)/STATES/$ID"
mkdir --parents "$STATE_PATH"
cp $COMMITABLE "$STATE_PATH"
ln -s "$STATE_PATH" PARENT

How could I achieve this in a batch file?

Here you go. This is from my own scripts:

set now=%date:~-4%-%date:~-10,2%-%date:~-7,2%-%time:~0,2%-%time:~3,2%-%time:~6,2%

rem Before 10:00 o'clock a space is used, this makes it a zero.
set now=%now: =0%

xcopy . copydir-%now% /i

One word of warning: this uses the US date format. For matching a different format you will have to change it. As I work with Dutch and US systems I personally use this code:

rem US date versus Dutch: test 5th char is /
if "%date:~-5,1%"=="/" (
   rem Date format is mm/dd/yyyy
   set now=%date:~-4%-%date:~-10,2%-%date:~-7,2%-%time:~0,2%-%time:~3,2%-%time:~6,2%
) else (
   rem Date format is dd-mm-yyyy
   set now=%date:~-4%-%date:~-7,2%-%date:~-10,2%-%time:~0,2%-%time:~3,2%-%time:~6,2%
)

xcopy 's /exclude:$FILE option can be used to specify a file containing filenames to be ignored. A friend of mine converted the script to batch like this:

@echo off
set thedate=%date:~0,2%-%date:~3,2%-%date:~6,4%
md %thedate%
echo STATES > excludefile.txt
echo excludefile.txt >> excludefile.txt
xcopy <root folder of directory structure> %thedate% /e /i /exclude:excludefile.txt
del excludefile.txt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM