Write a batch script that select the most recent file which was saved on a remote server.

Ouroboros DeFi "ODIE"
2 min readJun 15, 2023

--

To accomplish this task, you can use the robocopy command in a batch script to copy the files from the remote server to a local directory, and then use the dir command to find the most recent file in the local directory. Here's an example batch script that achieves this:

@echo off
set "remotePath=\\server\share\folder"
set "localPath=C:\Temp"
REM Copy files from remote server to local directory
robocopy "%remotePath%" "%localPath%" /E /Z /COPY:DAT /R:1 /W:1 /NP > nul
REM Change to the local directory
cd /D "%localPath%"
REM Find the most recent file
for /f "delims=" %%F in ('dir /B /O:-D') do (
set "mostRecentFile=%%~F"
goto :done
)
:done
echo The most recent file is: %mostRecentFile%

Make sure to replace \\server\share\folder with the actual path to the remote folder you want to access and C:\Temp with the desired local directory path where you want to copy the files.

The script uses robocopy with the /E flag to copy all files and subdirectories, /Z to copy files in restartable mode, /COPY:DAT to copy data, attributes, and timestamps, /R:1 to retry once in case of failures, and /W:1 to wait 1 second between retries. The /NP flag prevents robocopy from displaying the progress of the file copy.

After copying the files, the script changes to the local directory using cd /D "%localPath%" and then uses the dir command with the /B flag to list only the file names in the directory, and the /O:-D flag to sort them in descending order by date. The for /f loop captures the first file in the sorted list, which will be the most recent file, and assigns it to the mostRecentFile variable. Finally, the script prints the name of the most recent file.

Note that the script assumes that you have proper access rights to the remote server and the local directory. Additionally, the script does not handle cases where there are no files in the remote server or if the remote server is unreachable. You can add error handling or modify the script further based on your specific requirements.

Free Research Preview. ChatGPT may produce inaccurate information about people, places, or facts. ChatGPT May 24 Version

--

--