I have the below code which gets the last modified file from "AX copy" and compares it with the last modified file in "Reflex copy". It then outputs the difference in Error.
I need the output copy to have the same name as the input file from "AX copy". I have used something to declare the file name again and assign it to the output. however I have a problem, when delcaring it in the below code, it uses the oldest file name.
Please can someone adjust the code so the output copy has the same name as the input from the "AX copy" folder. My code is:
@echo off
cd /d C:\Users\Important Structure\Development\AX copy
for /f %%a in ('dir /b /o-d /a-d /tw') do (set latest=%%a)
setlocal enableextensions disabledelayedexpansion
call :getLatestFileInFolder "C:\Users\Important Structure\Development\AX copy" latestC
call :getLatestFileInFolder "C:\Users\Important Structure\Development\Reflex copy" latestD
if not defined latestC ( echo NO File in C & exit /b )
if not defined latestD ( echo NO File in D & exit /b )
for /f "tokens=1,*" %%a in (
'diff "%latestC%" "%latestD%" ^| findstr /r /c:"^<" /c:"^>"'
) do (
>> "C:\Users\Important Structure\Development\Error\%latest%" echo(%%b
)
endlocal
exit /b
:getLatestFileInFolder folderToSearch variableToReturn
setlocal
set "folder=%~1" & if not defined folder set "folder=%cd%"
set "latest="
pushd "%folder%"
for /f "tokens=*" %%a in ('dir /b /o-d /a-d /tw 2^>nul') do (set "latest=%%~fa" & goto :latestFileFound)
:latestFileFound
popd
endlocal & set "%~2=%latest%" & goto :eof
In this line
for /f %%a in ('dir /b /o-d /a-d /tw') do (set latest=%%a)
The dir command in listing file in date descending order. On first iteration (the first file), the latest file is assigned to the variable, but for command does not stop here, and continues iterating over the rest of the files. So, at end, the variable contains the oldest file in folder.
To solve it , you can list the files in ascending date order (change /o-d
to /od
), or use the included subroutine
call :getLatestFileInFolder "C:\Users\Important Structure\Development\AX copy" latest
Which, as the code is working, is the same that Matt has indicated to you. %latest%
is the same file that %latestC%
Why does it not work. diff command has to open the file to read, so, probably, you can not write to it while diff has it locked.
To solve it, select a temporary file (set "tempFile=%temp%\%~nx0.tmp"
), write the generated diff to this temporary file and then append this temporary file to the original file (type "%tempFile%" >> "%latest%"
) or overwrite it if the previous content is not needed (type "%tempFile%" > "%latest%"
)