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

1

I have this structure:

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

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

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

How to program the batch? I tried this code but it is incomplete because it does not find the 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%"
    )
    
asked by anonymous 10.11.2015 / 15:48

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!
    )
    )
    )
    
10.11.2015 / 17:57