Batch to locate a subfolder, move all files to a level above and delete the folder

Asked

Viewed 686 times

1

I have this structure:

    ..
    ..\FolderA\FolderX\File1.txt
    ..\FolderB\FolderX\File2.txt
    ..\FolderC\FolderD\FolderE\FolderX\File3.txt

I need a batch to locate all "Folderx" folders in the subdirectories and move all files to a level above and delete the "Folderx" folder"

    ..
    ..\FolderA\File1.txt
    ..\FolderB\File2.txt
    ..\FolderC\FolderD\FolderE\File3.txt

How to program batch? I tried this code, but it is incomplete as it does not locate folders.

    @Echo Off
    Set _Source=%~dp0
    Set _FindDir=FolderX
    Set _Path=%_Source%\%_FindDir%
    If Exist "%_Path%" (
    Move /-Y "%_Path%\*.*" "%_Source%"
    For /F "Tokens=* Delims=" %%I In ('Dir /AD /B "%_Path%"') Do Move "%_Path%\%%I" "%_Source%"
    RD /S /Q "%_Path%"
    )

1 answer

1

Solved with the following code:

    @echo off & setlocal enabledelayedexpansion
    for /d /r %~dp0 %%a in (*) do (
    if /i "%%~nxa"=="FolderX" (
    set "folderpath=%%a" (
    move /y !folderpath!\* !folderpath:~,-8!
    rmdir !folderpath!
    )
    )
    )

Browser other questions tagged

You are not signed in. Login or sign up in order to post.