Here is how to loop files in windows with batch and execute some commands.
This becomes really handy if you want to convert some files, change file extensions, compress files or anything else.
[codesyntax lang=”winbatch”]
FOR /R “C:\MyDir\” %%G in (*.txt) do echo %%G
[/codesyntax]
/R means traverse through all subfolders.
The first argument is the base folder to start in.
%%G is a variable, where the letter G can be changed according to your needs.
(*.txt) is the file filter.
This could also be expanded to execute multiple commands with the use of ( )
[codesyntax lang=”winbatch”]
FOR /R “C:\MyDir\” %%G in (*.txt) do (
echo %%G
echo “hello”
)
[/codesyntax]
If you want to chose a parameter that you gave the script, use %1 – %9 to select the parameter number.
%0 is the batch filename.
To access the variables beyong %9, you need to use the shift
Shift is able to shift the parameters to the left.
For example:
[codesyntax lang=”winbatch”]
shift /3
[/codesyntax]
shifts all to the left, and doesn’t alter %0–%2 but all the following parameters.
%3 will be set to the former value of %4, %4 to %5, %5 to %6… and %9 to the before inaccessible %10.
If you want to alter the variables, you could use one of the following codes (the number “1” needs to be replaced by your variable name… G for example):
%~1
Expands %1 and removes any surrounding quotation marks (“”).
%~f1
Expands %1 to a fully qualified path name.
%~d1
Expands %1 to a drive letter.
%~p1
Expands %1 to a path.
%~n1
Expands %1 to a file name.
%~x1
Expands %1 to a file extension.
%~s1
Expanded path contains short names only.
%~a1
Expands %1 to file attributes.
%~t1
Expands %1 to date and time of file.
%~z1
Expands %1 to size of file.
%~$PATH:1
Searches the directories listed in the PATH environment variable and expands %1 to the fully qualified name of the first one found. If the environment variable name is not defined or the file is not found, this modifier expands to the empty string.
%~dp1
Expands %1 to a drive letter and path.
%~nx1
Expands %1 to a file name and extension.
%~dp$PATH:1
Searches the directories listed in the PATH environment variable for %1 and expands to the drive letter and path of the first one found.
%~ftza1
Expands %1 to a dir-like output line.