Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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?

share|improve this question
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 '11 at 9:54
add comment

2 Answers

up vote 3 down vote accepted

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.

(...)
share|improve this answer
    
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 '11 at 13:57
add comment

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.

share|improve this answer
    
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 '11 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%. –  grawity Sep 21 '11 at 14:11
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.