简体   繁体   中英

Command rmdir in batch script file not working properly

I need move and then delete directories where file was located from disk. The structure looks like that:

./Export
  /Report_1
    /12345
      /something.pdf
  /Report_2
  ...

My code looks like this:

@echo off
SETLOCAL ENABLEDELAYEDEXPANSION

cd Export
for /D %%I in (%~dp0Export\*) do (
    set "input=%%~nI"
    for /f "tokens=2 delims=_" %%a in ("!input!") do (
        md %~dp0new_reports\new_report_%%a  
        cd Report_%%a
        for /R %%f in (*.pdf) do (
            for %%S in (%%f) do (
                if %%~zS NEQ "0" (
                    move %%f %~dp0new_reports\new_report_%%a
                    cd ..
                    set "id=%%a"
                    echo !id!
                    rmdir /S /Q "%~dp0Export\Report_!id!\"
                )
            )
        )
    )
)
@echo Finished ....

But rmdir deletes only subfolder with ID ( /12345 ), but Report_1 folder is still there, but is empty. I tried echo "%~dp0Export\\Report_!id!\\" and it looks ok.

So on the end of the script structure looks like this:

./Export
      /Report_1
      /Report_2
      ...

and I need remove folders Report_1 and so on, as well.

If I copy command to console it works but in batch script it is not working how I need.

Would something like this suit your purpose?

@Echo Off
SetLocal EnableDelayedExpansion
PushD "%~dp0Export" 2>Nul||Exit/B
For /D %%I in (*) Do (Set "input=%%~nxI"
    MD "new_reports\new_report_!input:*_=!"
    For /F "Delims=" %%f In ('Dir/B/S/A-D "%%~nxI\*.pdf"') Do If %%~zf Neq 0 (
        Move "%%f" "new_reports\new_report_!input:*_=!" && RD/S/Q "%%~nxI"))
Echo(Finished ....
Timeout -1

I have created the new directories inside the Export directory for now, just to keep everything together. Change "new_reports\\new_report_!input:*_=!" to "%~dp0new_reports\\new_report_!input:*_=!" in both locations to change to your preferred structure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM