2

I made this command to move specified files in all subfolders to a specified destination and then delete all empty subfolders.

Copying all PDF-files in subfolders into current dir

for /f "tokens=*" %d in ('dir *.pdf /b/s') do move /y "%d" .\

and then deleting all empty folders

for /f "tokens=*" %d in ('dir /ad/b/s ^| sort /R') do rd "%d"

The commands looks work well when I copy it and paste it into a command line, but not when I run it inside a batch file. What am I forgetting? And can I trust this command in all conditions?

1
  • 1
    if you want to know whether you can trust a FOR Command, and you should do this always.. write echo just after the DO so it dumps what is after echo to the console, so you can see what it would execute. (also when doing that, put an AT symbol before echo, like @echo)
    – barlop
    Nov 18, 2011 at 9:54

2 Answers 2

2

When for is used inside a batch script, you need to double the %.

C:\>for /?
(...)

To use the FOR command in a batch program, specify %%variable instead
of %variable.  Variable names are case sensitive, so %i is different
from %I.

(...)
1
  • Crazy me..! Of cours you have right!!! I think I spent too much time behind my PC for today.. Thanks a lot!!
    – Aziz
    Sep 21, 2011 at 13:57
0

The working directory when you run this script from the command line is %HOMEPATH% (or the directory you browsed to), running it from a script file uses the directory where the script is located as a home path. so the output won't be the same.

2
  • You mean also that I have to change ".\" with "%HOMEPATH%" when i want to move into current dir when running this command from a batch file? I just tryed it but it looks it work both way. I have the batch in my tools folder which is defined in PATH, and running it from any directory.
    – Aziz
    Sep 21, 2011 at 14:06
  • When running a program or script from the command line, it always inherits the shell's "working directory". It is never reset to %HOMEPATH%. Sep 21, 2011 at 14:11

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .