script to delete empty folders (comand line)

for /f "usebackq delims=" %%d in (`"dir /ad/b/s | sort /R"`) do rd "%%d"

this code works fine but only when the batch file is in the same directory
we want to use a variable in this code, or define the directory where to start the deletion process
Who is Participating?
Lee W, MVPConnect With a Mentor Technology and Business Process AdvisorCommented:
Then use

cd /d %1

/d indicates that CD should change to the drive letter as well.
Lee W, MVPTechnology and Business Process AdvisorCommented:
Add a line before it -

cd %1

Then to specify a directory, do so at the command line - for example, if you want to run this on the C:\TEMP folder, then you would type:

MyBatch.cmd "c:\temp"

c:\temp is then assigned to %1 (quotes are required if the folder has spaces, as a best practice, just ALWAYS put quotes around it).

the CD changes into C:\temp and now your command does what you want it to do at the appropriate folder.
HelpdeskJBCAuthor Commented:
it work wehen it is on the same partition, but
we would like to use it on a other partition (network drive)

batchfile on drive D:\ and it should run on V:\
Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

for /f "usebackq delims=" %%d in (`"dir %1 /b /o:-n /a:d"`) do rd %1"%%d"

I used
/o:-n to reverse sort it by Name (so you dont need to use Sort) (Not sure why you need this)
/a:d - To show only Folders.

use: DelEmpty.bat C:\Folder\

I hope this helps.
Please Ignore my comment. It's wrong and leew's way work's great.
If you're OK with starting it the batch file with a parameter.

filename.cmd V:\

Then try this.
for /f "delims=" %%d in ('dir "%1" /ad/b/s ^| sort /R') do rd "%%d"

Open in new window

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.