Not so random number in batch file

May 25, 2009 at 00:43:18
Specs: Windows 2003
I am looking to try and move files from one directory to another. When I move the files I want to rename them, Ideally I would like to timestamp them with the current time but a random number will work.

Here is my current code at the moment the files are moved but the random value does not seem to work.

@echo off
setLocal EnableDelayedExpansion

for /f "tokens=* delims= " %%a in ('dir/b/a-d *.mq') do (
echo move %%a C:\DEV\%random%%%a)

move TCLMD_97.mq C:\DEV\31070TCLMD_97.mq
move TCLMD_98.mq C:\DEV\31070TCLMD_98.mq
move TCLMD_99.mq C:\DEV\31070TCLMD_99.mq


Also I am hard coding the directory path could I set that as a value rather to make it easy to update ?


See More: Not so random number in batch file

Report •


#1
May 25, 2009 at 01:06:30
As the %Random% is in the for loop it will aways be the same value....

@echo off
setLocal EnableDelayedExpansion
set folder1=C:\DEV\usr1
set folder2=C:\DEV\usr2


for /f "tokens=* delims= " %%a in ('dir/b/a-d %folder2%\*.mq') do (
echo move %%a %folder2%\%Random%_%%a)


Report •

#2
May 25, 2009 at 03:08:57
To enable Delayed Expansion doesn't suffice: you must mark the dynamic variable by the ! symbol instead of the conventional %, so

!Random!


Report •

#3
May 25, 2009 at 19:05:18
Thanks for the hint !Random! worked just fine, Here is the script all works fine apart for if a "file is not found" I have been trying to trap for the error with out any luck.

@echo off
cls
setLocal EnableDelayedExpansion
set folder1=C:\DEV\movemsg\folder1
set folder2=C:\DEV\movemsg\folder2

echo.&echo.&echo.
echo Please wait while msg messages are moved...
echo.

for /f "tokens=* delims= " %%a in ('dir/b/a-d %folder1%\*.mq') do (
echo move %folder1%\%%a %folder2%\!Random!_%%a
set /a msgCOUNT +=1)


echo.&echo.&echo.
echo Moving of inbound msg messages from folder1 is complete.
echo.
echo msg messages moved = %msgCOUNT%
echo.
echo Press any key to continue.....
pause > nul


Report •

Related Solutions

#4
May 26, 2009 at 03:35:35
Just before the for /F loop add the following statements

  dir /B /A-D %folder1%\*.mq > nul 2>&1
  if ErrorLevel 1 (
    echo. &  echo.  No file found & echo.
    goto :DONE
  )

and insert the label :DONE before

echo Press any key to continue.....
pause > nul


Report •


Ask Question