只要父文件夹中没有文件,就将所有文件从“旧”文件夹移到父文件夹中

时间:2018-07-26 15:45:43

标签: batch-file

只要父文件夹中还没有文件,我的代码就应该将所有文件从“旧”文件夹移到父文件夹中。

└───Folder
    ├───1
    │   └───old
    │           somefiles
    ├───2
    │   └───old
    │           somefiles
    └───3
        └───old
                somefiles

└───Folder
    ├───1
    │   │   somefiles
    │   └───old
    ├───2
    │   │   somefiles
    │   └───old
    └───3
        │   somefiles
        └───old

到目前为止,我的代码将1个文件移到了父文件中(如果还没有文件),然后它停止了,因为父文件中现在已有文件了。

rem // Iterate over the changing directories:
for /D %%D in ("C:\testen\qft\*") do (
    rem // Iterate over the files to process:
    for %%F in ("%%~D\old\*.*") do (
        rem // Actually move the files one level up:
        dir /A:-D "%%~D" ||  move /Y "%%~F" "%%~dpF.."
    )
)

我试图解决这样的问题:

rem // Iterate over the changing directories:
for /D %%D in ("C:\testen\qft\*") do (
    rem // Iterate over the files to process:
    for %%F in ("%%~D\old\*.*") do (
        rem // Actually move the files one level up:
    dir /A:-D "%%~D" || set VAR="true"
    if "%VAR%" == "true" (
    move /Y "%%~F" "%%~dpF.."
    dir /A:-D "%%~F" || set VAR="false"
    )
    )
)

但是我的代码调整中必须留有一些错误,因为它不再正常工作。有人可以看到我的错误吗?

1 个答案:

答案 0 :(得分:2)

尝试中有两个问题:

  1. 在同一代码块中读写变量VAR时需要delayed expansion。如果将其更改为set "VAR=true"set "VAR="(空),则可以使用if defined VAR,它不需要延迟扩展;
  2. 不应在内部for循环中检查当前迭代目录的内容,因此在已有文件的情况下将跳过该内容;

这是一个可能的解决方案:

rem // Iterate over the changing directories:
for /D %%D in ("C:\testen\qft\*") do (
    rem // Check whether current directory contains files:
    dir /A:-D "%%~D\*.*" > nul 2>&1 || (
        rem // Iterate over the files to process:
        for %%F in ("%%~D\old\*.*") do (
            rem // Actually move the files one level up:
            move /Y "%%~F" "%%~dpF.."
        )
    )
)
相关问题