# Batch file to conditionally move files



## prescotblue (Jun 20, 2011)

Hi, please help!

I have a folder containing machine control files (*.ctl) and a separate folder for control update files (*.upd). The update files can only be applied AFTER the control files appear but they may be available in advance. The UPD files must be moved to the CTL folder AFTER the CTL file appears.

I need to create a batch file to move the UPD file only if the CTL file exists. I have read some similar posts and have had a go but I can't quite get there.

The files CTL and UPD have the same name prior to the extension so I need the batch file to read the upd folder and extract file name minus extension to use in an "if exists %filename%.ctl move %filename%.upd" type command.

Here is my effort which sort of works but I need to get the "if exist" statement within the For loop. In the example the upd files and batch file are in the folder D:\Temp and the CTL files in the folder c:\Temp

for /F %%a in ('dir /b *.upd') do set FileName=%%~na
echo %FileName%
if exist c:\temp\%FileName%.ctl move %Filename%.upd c:\temp
if %errorlevel% neq 0 goto escape
:escape exit 

Any help, please!
Dave


----------



## Ent (Apr 11, 2009)

I assume that you need to work through all the .upd files. That means that you need the for loop to affect the entire section, not just the Set Filename=%%~na part. To do so, use parentheses.
 Secondly, rather than getting the input from the dir command we might as well get it straight from the folder. That means putting only *.upd in where you had 'dir /b *.upd' and removing the /F switch.
Thirdly it's always wise when referring to files and folders to put them in quotes. Otherwise you risk the command breaking on something with a space such as _My Documents_.
For simplicity I've had the script avoid using the Set command and simply get the filename section of %%a twice.
Lastly once out of the testing phase it's almost always worth putting _@echo off_ at the start, just to stop the computer repeating your every command back to you.


```
[COLOR=Purple] @echo off[/COLOR]
for %%a in ([COLOR=Red]*.upd[/COLOR]) do [COLOR=DarkGreen][U]([/U][/COLOR]
if exist [COLOR=Lime]"c:\temp\[COLOR=DarkOrange]%%~na[/COLOR].ctl[/COLOR][COLOR=Lime]"[/COLOR] move [COLOR=Lime]"[COLOR=DarkOrange]%%~na[/COLOR].upd" "c:\temp\"[/COLOR]
if %errorlevel% neq 0 goto escape
[COLOR=DarkGreen][U])[/U][/COLOR]
pause
:escape
exit
```


----------

