这是此任务的注释批处理代码:
@echo off
setlocal
rem Define source and backup path.
set "SourcePath=C:\machines\models"
set "BackupPath=E:\backup"
rem Get current date in format YYYY-MM-DD independent on local date format.
for /F "skip=1 tokens=1 delims=." %%T in ('%SystemRoot%\System32\wbem\wmic.exe OS get localdatetime') do set LocalDateTime=%%T & goto ReformatDate
:ReformatDate
set "YearMonthDay=%LocalDateTime:~0,4%-%LocalDateTime:~4,2%-%LocalDateTime:~6,2%
rem For each subfolder in source path check if there is a subfolder "defects".
rem If subfolder "defects" exists, copy all files and subfolders of "defects"
rem to the appropriate backup directory with current date and subfolder name
rem in source folder path. Then remove the subfolder "defects" in source
rem folder even if being completely empty to avoid processing this folder
rem again when not being recreated again in the meantime.
for /D %%# in ("%SourcePath%\*") do (
if exist "%%#\defects\*" (
%SystemRoot%\System32\xcopy.exe "%%#\defects\*" "%BackupPath%\%YearMonthDay%\%%~nx#_defects\" /H /I /K /Q /R /S /Y >nul
rd /Q /S "%%#\defects"
)
)
endlocal
在命令提示符窗口wmic OS get localdatetime 中运行一次以查看此命令输出的内容,以更好地了解当前日期是如何以YYYY-MM-DD 格式确定的。使用%DATE% 会更快,但%DATE% 的日期字符串格式取决于Windows 区域和语言设置中设置的国家/地区,因此需要了解运行此批处理文件的计算机上的日期字符串格式。
如果models 目录中有defects 子文件夹,则带有使用选项的命令XCOPY 不会在备份目录中创建子文件夹,但在整个defects 子文件夹树中存在至少要复制 1 个文件。
使用环境变量 DATE 的替代代码,期望扩展的日期字符串以:MM/DD/YYYY 结尾,例如Tue 05/17/2016,详细解释于:
What does %date:~-4,4%%date:~-10,2%%date:~-7,2%_%time:~0,2%%time:~3,2% mean?
@echo off
setlocal
rem Define source and backup path.
set "SourcePath=C:\machines\models"
set "BackupPath=E:\backup"
rem Get current date in format YYYY-MM-DD depending on local date format.
set "YearMonthDay=%DATE:~-4,4%-%DATE:~-10,2%-%DATE:~-7,2%"
rem For each subfolder in source path check if there is a subfolder "defects".
rem If subfolder "defects" exists, copy all files and subfolders of "defects"
rem to the appropriate backup directory with current date and subfolder name
rem in source folder path. Then remove the subfolder "defects" in source
rem folder even if being completely empty to avoid processing this folder
rem again when not being recreated again in the meantime.
for /D %%# in ("%SourcePath%\*") do (
if exist "%%#\defects\*" (
%SystemRoot%\System32\xcopy.exe "%%#\defects\*" "%BackupPath%\%YearMonthDay%\%%~nx#_defects\" /H /I /K /Q /R /S /Y >nul
rd /Q /S "%%#\defects"
)
)
endlocal
要了解所使用的命令及其工作原理,请打开命令提示符窗口,在其中执行以下命令,并仔细阅读每个命令显示的所有帮助页面。
echo /?
endlocal /?
-
for /? ... 还解释了 %%~nx#(模型子文件夹的名称(和扩展名))。
if /?
rd /?
set /?
setlocal /?
wmic.exe OS get /?
xcopy /?
另请参阅有关Using command redirection operators 的Microsoft 文章以了解>nul 的含义。
为什么%%~nx# 而不仅仅是%%~n# 因为文件夹没有文件扩展名?
Windows 命令处理器无法确定字符串是文件夹还是文件名。最后一个反斜杠之后的所有内容都被解释为文件名,独立于文件或文件夹的真实名称。并且字符串中最后一个反斜杠之后的最后一个点之后的所有内容都被解释为 文件扩展名,即使这意味着使用 %~n 引用的文件夹或文件名是一个空字符串,因为文件夹/文件名以dot 并且不像 *nix 系统上的许多“隐藏”文件那样包含一个点,例如.htaccess。因此,如果在命令行中需要文件夹或文件的全名,则应始终使用%~nx。