Help with %random% in a batch file

February 23, 2011 at 07:58:25
Specs: Windows 7
Here is what I am trying to do:

I need to copy all .log files from all subdirectory's on a server folder to a single directory on a different disk. The issue is this ..\folder1\log1.log and ...\folder2\log1.log have the same file name and cause the batch file to prompt for overwrite. I don’t care if every file gets appended with a random number to make the file names unique. here is what I have:

for /f "delims=" %%a in ('dir c:\*.log /s /b 2^>NUL') do copy "%%a" "d:\stuff2\%random%*.*"

The issue is that this is only getting one random number and is appending every file with the same number. I run into the same issue with duplicate names in the target directory as I did before.

Is there any way to make that random number either change, or increment? Is there a better way to do what I am trying?

Thank you very much!


See More: Help with %random% in a batch file

Report •

#1
February 23, 2011 at 08:53:26
@echo off & setlocal EnableDelayedExpansion
for /f "delims=" %%a in ('dir c:\*.log /s /b 2^>NUL') do copy "%%a" "d:\stuff2\!random!*.*"

To refer to environment variables inside a FOR loop you need to enable the Delayed Expansion then mark the variables by ! instead of the usual %. Type SET /? at prompt to know more.

Report •

#2
February 23, 2011 at 10:26:25
You are awesome. It worked! Just one more issue i am a little confused about. When I run that script it changes readme.log to 5787me.log. Is there a simple way of having it spit out the file names as 5787readme.log instead of overwriting the first part of the file name with the random integer?

Thank you very much!


Report •

#3
February 23, 2011 at 11:59:43
for /f "delims=" %%a in ('dir c:\*.log /s /b 2^>NUL') do copy "%%a" "d:\stuff2\%%~na_!random!%%~xa"


Report •

Related Solutions

#4
February 23, 2011 at 12:38:45
That works great! I learned a lot from this script, and it has saved me a ton of time. Thank you very, very much this was more helpful than I can express!

Report •

Ask Question