当源是目录时,xcopy command 复制其内容而不是整个目录。要复制整个目录,您需要相应地更改目标:
xcopy /I /Y /S "%src_folder%\%%f" "%dst_folder%\%%f"
注意/I 选项,它告诉xcopy 目标不是文件而是目录。
但是,当源是单个文件时,xcopy 会在目标尚不存在时提示您目标是文件还是目录,即使提供了/I(请参阅this related post)。因此,我们必须提前确定来源(%%f)是什么,并做出充分的反应:
@echo off
rem // The quoted `set` syntax protects special characters:
set "src_folder=C:\Users\P57949\Desktop"
set "dst_folder=C:\Users\P57949\Desktop\NewTestFolder"
set "file_list=C:\Users\P57949\Desktop\Filelist.txt"
rem // Append `\*` to check a directory but not a file for existence:
if not exist "%dst_folder%\*" mkdir "%dst_folder%"
rem // Use `usebackq` option and quotation to permit spaces in file path:
for /F "usebackq delims=" %%f in ("%File_list%") do (
rem // Check whether source is a directory:
if exist "%src_folder%\%%f\*" (
rem // Source is a directory, so copy it entirely:
xcopy /I /Y /S "%src_folder%\%%f" "%dst_folder%\%%f"
) else (
rem // Source is a file, or it does not exist:
xcopy /Y /S "%src_folder%\%%f" "%dst_folder%\"
)
)
预先创建目标文件时可以实现更简单更紧凑的方法,因此不会出现文件/目录提示:
@echo off
rem // The quoted `set` syntax protects special characters:
set "src_folder=C:\Users\P57949\Desktop"
set "dst_folder=C:\Users\P57949\Desktop\NewTestFolder"
set "file_list=C:\Users\P57949\Desktop\Filelist.txt"
rem // Append `\*` to check a directory but not a file for existence:
if not exist "%dst_folder%\*" mkdir "%dst_folder%"
rem // Use `usebackq` option and quotation to permit spaces in file path:
for /F "usebackq delims=" %%f in ("%File_list%") do (
rem // Pre-create destination file when source is a file:
if not exist "%src_folder%\%%f\*" > "%dst_folder%\%%f" rem/
rem // No prompt appears even when source is a file:
xcopy /I /Y /S "%src_folder%\%%f" "%dst_folder%\%%f"
)
最简单的方法是使用/I 选项来覆盖源是目录的情况,并自动填充源是文件的情况下的文件/目录提示,但这是区域设置相关的(例如,File 和 Dictory 用于英语系统,Datei 和 Verzeichnis 用于德语系统),所以要小心:
@echo off
rem // The quoted `set` syntax protects special characters:
set "src_folder=C:\Users\P57949\Desktop"
set "dst_folder=C:\Users\P57949\Desktop\NewTestFolder"
set "file_list=C:\Users\P57949\Desktop\Filelist.txt"
rem // Append `\*` to check a directory but not a file for existence:
if not exist "%dst_folder%\*" mkdir "%dst_folder%"
rem // Use `usebackq` option and quotation to permit spaces in file path:
for /F "usebackq delims=" %%f in ("%File_list%") do (
rem // The `/I` option copes for directories, `echo F` for files:
rem echo F| xcopy /I /Y /S "%src_folder%\%%f" "%dst_folder%\%%f"
)
N. B.:
对于以上所有内容,我假设列表文件 Filelist.txt 包含纯文件/目录名称。