如何在运行XCOPY时识别目标文件夹中的更新文件?



>我创建了一个批处理文件,用于将更新的文件从源文件夹同步到目标文件夹。它正在完美地工作。现在,我想在每次运行脚本时识别(或复制到文件夹)目标文件夹中的更新文件,以便它可以用于某些操作。

有没有办法实现这一目标?

复制.bat

xcopy E:sss q:  /c /d /e /h /i /k /q /r /s /y

在运行XCOPY命令之前,从所有目录中的所有文件中递归 archive 属性Q:在目标目录中删除。然后运行XCOPY将所有较新的文件复制到Q:.最后处理在目标目录中设置了存档属性的所有文件,这些文件是XCOPY复制的文件。

示例批处理文件只是在复制较新的文件后将具有存档属性设置的文件打印到控制台窗口中:

@echo off
%SystemRoot%System32attrib.exe -A Q:* /S
%SystemRoot%System32xcopy.exe E:sss Q: /C /D /E /H /I /K /Q /R /S /Y >nul
for /F "delims=" %%I in ('dir Q:* /AA-D /B /S 2^>nul') do echo %%I

要了解使用的命令及其工作原理,请打开命令提示符窗口,在那里执行以下命令,并仔细阅读为每个命令显示的所有帮助页面。

  • attrib /?
  • dir /?
  • echo /?
  • for /?
  • xcopy /?

另请阅读有关使用命令重定向运算符的Microsoft文章。

要列出实际复制的所有文件,您可以将开关/Q(不显示文件名)替换为/F(显示完整的源文件名和目标文件名),并从输出中提取目标路径,如以下示例所示(请参阅所有解释性注释):

@echo off
setlocal EnableExtensions DisableDelayedExpansion
rem // Define constants here:
set "_SOURCE=E:sss" & rem // (path to source directory)
set "_TARGET=Q:\"   & rem // (path to destination directory)
rem /* Run `xcopy` to do its job (remove `/L` to actually copy files); the `/F` option
rem    lets `xcopy` output the full source and destination paths of each file copied,
rem    separated from each other by ` -> `; hence split each line at this separator to
rem    extract the destination path; `find` filters out the final summary line (like
rem    `?? File(s)`); `for /F` finally captures the output of `xcopy`: */
for /F "delims=" %%F in ('
xcopy "%_SOURCE%" "%_TARGET%" /C /D /E /H /I /K /F /R /Y /L ^| find ">"
') do (
rem // Store current line (source and destination paths) in variable:
set "FILE=%%F"
rem // Toggle delayed expansion to avoid trouble with exclamation marks:
setlocal EnableDelayedExpansion
rem // Split current line at said separator to retrieve the destination path:
set "FILE=!FILE:* -> =!"
rem // Return the extracted destination path:
echo/!FILE!
endlocal
)
endlocal
exit /B

不要忘记从xcopy中删除/L(列出要复制的文件)选项以实际复制任何文件。

如果要将文件列表写入文本文件(例如,批处理文件目录中的filelist.txt),请使用以下代码(这次省略了大多数注释):

@echo off
setlocal EnableExtensions DisableDelayedExpansion
rem // Define constants here:
set "_SOURCE=E:sss" & rem // (path to source directory)
set "_TARGET=Q:\"   & rem // (path to destination directory)
set "_LISTFILE=%~dp0filelist.txt" & rem // (path to list file)
rem // Redirect output of whole `for /F` loop to a text file:
> "%_LISTFILE%" (
for /F "delims=" %%F in ('
xcopy "%_SOURCE%" "%_TARGET%" /C /D /E /H /I /K /F /R /Y /L ^| find ">"
') do (
set "FILE=%%F"
setlocal EnableDelayedExpansion
set "FILE=!FILE:* -> =!"
echo/!FILE!
endlocal
)
)
endlocal
exit /B

最新更新