Near the end of the output from SET /?
is this gem about delayed environment variable extraction. It shows how to use a relatively new notation (since NT 3.1? it works in XP and Win 7) for delayed expansion of an environment variable to build a list of file names matching a wild card in a single variable.
Delayed environment variable expansion allows you to use a different
character (the exclamation mark) to expand environment variables at
execution time. If delayed variable expansion is enabled, the above
examples could be written as follows to work as intended:
set LIST=
for %i in (*) do set LIST=!LIST! %i
echo %LIST%
Note that there is an issue here with quoting of names containing spaces or other "interesting" characters that I've left as an exercise for the student. Getting quoting right in CMD.EXE is even harder than getting it right in any Unix shell.
Naturally, replace the echo
command with your command line.
Edit: It has been observed that this doesn't seem to work as well in a batch file, and it depends on the specific feature of delayed expansion being enabled.
The delayed expansion feature is enabled with the /V:ON
switch to CMD.EXE, or globally for all invocations of CMD by an registry key. The details are documented in the output of CMD /?
.
Moving to a batch file, you have a couple of issues, and an easy fix for enabling the feature. The key is that the SETLOCAL
command has an option to turn the delay feature on and off at will. From CMD /?
:
In a batch file the SETLOCAL ENABLEDELAYEDEXPANSION
or DISABLEDELAYEDEXPANSION
arguments takes precedence over the /V:ON
or /V:OFF
switch. See SETLOCAL /?
for details.
Also, there is the cryptic need to double the percent signs in some contexts, such as FOR
commands. All together, I'd rewrite my example like this:
SETLOCAL ENABLEDELAYEDEXPANSION
set LIST=
for %%f in (*.ts) do set LIST=!LIST! "%%f"
echo %LIST:~1%
The above also quotes each file name to deal with names that have spaces in them, and trims the extra space off the front of the string that was left there by the first loop iteration with %LIST:~1%
.