filebatch-filegotorobocopy

delete files when already in the destination folder


I have the code below that transfers the xml to the folder according to the year and month, but sometimes the file has already been copied to the destination folder, how can I inform the code to delete the file if it already exists?

@ECHO off
set v_day_of_week=
set v_day=
set v_month=
set v_year=
set v_path=

set v_pathOri=d:\XmlRec\
set v_sub_path = 
set v_copy_path = D:\xml\

SETLOCAL ENABLEEXTENSIONS
for /f "tokens=1" %%t in ('date/t') do (
    set v_day_of_week=%%t
    if "%%ta" LSS "a" (set toks=1-3) else (set toks=2-4)
)

::DEBUG echo toks=%toks%

for /f "tokens=2-4 delims=(-)" %%a in ('echo:^|date') do (

    ::DEBUG echo first token=%%a

    if "%%a" GEQ "A" (
        for /f "tokens=%toks% delims=.-/ " %%i in ('date/t') do (
            set '%%a'=%%i
            set '%%b'=%%j
            set 'yy'=%%k
        )
    )
)
if %'yy'% LSS 100 set 'yy'=20%'yy'%
set Today=%'yy'%-%'mm'%-%'dd'%
ENDLOCAL & SET day_of_week=%v_day_of_week% & SET v_year=%'yy'%& SET v_month=%'mm'%& SET v_day=%'dd'%

::ECHO Today is Year: %V_Year% Month: [%V_Month%] Day: [%V_Day%]

set datestring=%V_Year%%V_Month%%V_Day%

::echo %datestring%
::echo day of week=%day_of_week%

if %V_Month% == 01 set v_sub_path=01-Janeiro
if %V_Month% == 02 set v_sub_path=02-Fevereiro
if %V_Month% == 03 set v_sub_path=03-Marco
if %V_Month% == 04 set v_sub_path=04-Abril
if %V_Month% == 05 set v_sub_path=05-Maio
if %V_Month% == 06 set v_sub_path=06-Junho
if %V_Month% == 07 set v_sub_path=07-Julho
if %V_Month% == 08 set v_sub_path=08-Agosto
if %V_Month% == 09 set v_sub_path=09-Setembro
if %V_Month% == 10 set v_sub_path=10-Outubro
if %V_Month% == 11 set v_sub_path=11-Novembro
if %V_Month% == 12 set v_sub_path=12-Dezembro

set v_path=%v_pathOri%%V_Year%\%v_sub_path% 

if exist %v_pathOri%*.xml %v_path% (del %v_pathOri%*.xml)
else (  
    xcopy %v_pathOri%*.xml %v_path% /R  
    xcopy %v_pathOri%*.xml D:\xml\ /R
)

:EOF    

I tried to insert the code below, but even so, when executing the batch, the message appears:

if exist %v_pathOri%*.xml %v_path% (del %v_pathOri%*.xml)
else (  
    xcopy %v_pathOri%*.xml %v_path% /R  
    xcopy %v_pathOri%*.xml D:\xml\ /R
'd:\XmlRec\2024\01-Janeiro' is not recognized as an internal or external command,
operable program or batch file.
'else' is not recognized as an internal or external command,
operable program or batch file.
Overwrite D:\XmlRecebidos\2024\01-Janeiro\31240117550000013036511650115590.xml (Yes/No/All)?

Solution

  • I removed this part:

    if exist %v_pathOri%*.xml %v_path% (del %v_pathOri%*.xml)
    if not exist %v_pathOri%*.xml (
          xcopy %v_pathOri%*.xml %v_path% /R    
          xcopy %v_pathOri%*.xml D:\xml\ /R    )
    

    And I put /y at the end of the line and it worked

    set v_path=%v_pathOri%%V_Year%\%v_sub_path% 
    xcopy %v_pathOri%*.xml %v_path% /R /Y
    xcopy %v_pathOri%*.xml D:\xml\ /R /Y