批处理 - 为什么不重命名存档?

时间:2016-08-18 10:25:27

标签: batch-file

因此,众所周知,当我们使用批处理文件将存档移动到文件夹时,存在同名的另一个存档,批处理脚本将只替换旧存档。

由于我正在建立Archivating系统,这非常糟糕,因为重要数据可能会在归档过程中丢失,因此,我在SO中制作了票据,以获取有关如何解决此问题的信息。这是我的测试代码:

set year=%DATE:~6,4%

if not exist "V:\01_%YEAR%" mkdir "V:\01_%YEAR%"  - Creates folder 01_2016
for /d %%X in (01_%YEAR%) do "C:\Program Files\7-Zip\7z.exe" a "%%X.7z" "%%X\" - Archivates folder
MOVE "V:\01_%YEAR%.7z" "Z:\"  - moves Archive.

名为elzooilogico的用户,建议使用此命令代替Move命令:

set "last=0"
set "filename=Z:\01_%YEAR%.7z"

if exist "Z:\01_%YEAR%.7z" (
    for /R %%i in ("Z:\01_%YEAR%(*).7z") do (
       for /F "tokens=2 delims=(^)" %%a in ("%%i") do set "last=%%a"
    )
    set/a last+=1
    set "filename=Z:\01_%YEAR%(%last%).7z"    
)    

MOVE "V:\01_%YEAR%.7z" "%filename%"

不幸的是,我仍然不明白,为什么代码不起作用,所以我重新制作了一下,这就是我想出来的。

set YEAR=%DATE:~6,4%
set filename=C:\Users\PP_lemev\Desktop\New folder\01_%YEAR%.7z

cd /d C:\Users\PP_lemev\Desktop\New folder
if not exist "C:\Users\PP_lemev\Desktop\New folder\01_%YEAR%" mkdir "C:\Users\PP_lemev\Desktop\New folder\01_%YEAR%"
for /d %%X in (01_%YEAR%) do "C:\Program Files\7-Zip\7z.exe" a "%%X.7z" "%%X\"
    if exist "C:\Users\PP_lemev\Desktop\New folder\vairis\01_%YEAR%.7z" (
       for /R %%i in ("C:\Users\PP_lemev\Desktop\New folder\01_%YEAR%(*).7z") do (
          for /F "tokens=2 delims=(^)" %%a in ("%%i") do set "last=%%a"
    )
    set/a last+=1
    set "C:\Users\PP_lemev\Desktop\New folder\01_%YEAR%(%last%).7z"    
)    
MOVE "%filename%" "C:\Users\PP_lemev\Desktop\New folder\vairis" 

有人可以向我解释,为什么档案名称在脚本检查后没有重命名,如果存档已存在?

问候,Vairis

1 个答案:

答案 0 :(得分:1)

  

好的,新方法

@echo off
SetLocal EnableDelayedExpansion

set/a last=1
set "YEAR=%DATE:~6,4%"
set "myFolder=C:\Users\PP_lemev\Desktop\New folder\vairis"
set "filename=%myFolder%\01_%YEAR%.7z"

if exist "%myFolder%\01_%YEAR%.7z" (
  for /R %%i in ("%myFolder%\01_%YEAR%(*).7z") do set/a last+=1
  set "last=000!last!"
  set "filename=%myFolder%\01_%YEAR%(!last:~-4!).7z"    
)    

for /d %%X in (01_%YEAR%) do "C:\Program Files\7-Zip\7z.exe" a "%filename%" "%%X\"

endlocal