Need help understanding batch commands/parameters


  1. Posts : 15
    Windows 7 64-bit
       #1

    Need help understanding batch commands/parameters


    Hello,

    In this batch program (deletes temp files):

    @echo off
    cd %temp%
    for /d %%D in (*) do rd /s /q "%%D"
    del /f /q *

    What does the "%%D" component signify and how is it used? Or rather, how does the "for" command work for that matter? I've looked at other explanations online and I can't seem to find a clear distinction between %%D and %D, for example.

    I appreciate any input. Thanks.
      My Computer


  2. Posts : 721
    Windows 10, Windows 8.1 Pro, Windows 7 Professional, OS X El Capitan
       #2

    In a batch for loop, this "%%D" signifies a dynamic variable that will expand to each item of a list of data that For produces. In this example, %%D expands to each directory found within the %temp% folder.

    The for /d in (*) part of the command says to grab a list of all directories in the current working directory (which is %temp% in this case), and the command part of the loop: rd /s /q "%%D" is executed a finite number of times, where %%D expands to each item of data with each iteration of the loop.

    The letter proceeding the percents is completely arbitrary. It does not have to be capital, or even a letter at all. The following are examples of valid dynamic variable names; %%A, %%h, %%6, %%0, %%#, %%_, %%$. Though, it's always best practice to use a capital letter; it's rare you'll come across anything else.

    The writer of this batch script has appropriately chosen the letter D for its dynamic variable, as each iteration of the loop should expand %%D to a name of a directory.

    "%D" does not exist within batch files. A single percent is used when you want to run the For command within a Command Prompt. So if you want to run for /d %%D in (*) do rd /s /q "%%D" in a Command Prompt, it would become for /d %D in (*) do rd /s /q "%D". It's just something you have to remember.


    You may enter help for into a Command line to read more about the For loop. Or you can learn how to effectively use batch For Loops here.
      My Computer


 

  Related Discussions
Our Sites
Site Links
About Us
Windows 7 Forums is an independent web site and has not been authorized, sponsored, or otherwise approved by Microsoft Corporation. "Windows 7" and related materials are trademarks of Microsoft Corp.

© Designer Media Ltd
All times are GMT -5. The time now is 21:38.
Find Us