- 1 year ago
Iterate files in a directory - emitting commands with arguments containing %
To iterate through files in a directory in a Windows batch script and emit commands with arguments containing %
, you need to handle special characters properly to prevent issues with variable expansion. Here's an example batch script that demonstrates how to do this:
batch@echo off
setlocal enabledelayedexpansion
rem Set the directory path to iterate through
set "directory=C:\your\directory\path"
rem Loop through the files in the directory
for %%F in ("%directory%\*") do (
rem Check if the file is a regular file (not a directory)
if not "%%~aF"=="d" (
rem Emit your command here with arguments containing %%
echo YourCommand.exe "%%~dpnxF" "Some Argument with %%"
)
)
endlocal
Replace YourCommand.exe
with the name of your executable, and adjust the arguments accordingly. The %%~dpnxF
expands to the full drive, path, name, and extension of the current file in the loop, and %%
within double quotes will be treated as a literal %
.
The setlocal enabledelayedexpansion
is used to enable delayed expansion of variables, which allows you to handle special characters like %
correctly.
Please note that if the command you're emitting contains additional special characters, you may need to escape or handle them appropriately to prevent issues with variable expansion.