I'm trying to create a little batch script to run via task scheduler but running into an issue with the multiple PDF files in the same directory.
My aim is:
- map the remote NAS (this is to take load off the server, and as a backup)
- move the existing PDFs into an archive folder (of the same directory) except newest 2 files
- clean the archive to delete the oldest n
- email the attachments to my address
- unmount the NAS
The code so far:
:: delete the old mapping
NET USE A: /DELETE
:: map the backup location
NET USE A: \\NAS\Share\BU
:: set the time and date YYYYMMDD-HHMMSS.UUU
for /F "usebackq tokens=1,2 delims==" %%i in (`wmic os get LocalDateTime /VALUE 2^>NUL`) do if '.%%i.'=='.LocalDateTime.' set ldt=%%j
set ldt=%ldt:~0,4%%ldt:~4,2%%ldt:~6,2%-%ldt:~8,2%%ldt:~10,2%%ldt:~12,6%
:: archive older than the last one - local
pushd "C:\Users\Administrator\Documents\My Database Backups"
echo :: Move these files ::
echo ------------------------
for /f "skip=2 eol=: delims=" %%F in ('dir /b /o-d *.pdf') do MOVE "%%F" ".\archive"
:: clean the archive folder - local
echo :: Delete these files ::
echo ------------------------
pushd "C:\Users\Administrator\Documents\My Database Backups\archive"
for /f "skip=46 eol=: delims=" %%a in ('dir /a-d /o-d /b /s *.pdf') do del "%%a"
:: go to export directory
cd "C:\Users\Administrator\Documents\My Database Backups"
:: copy to NAS
copy /b *.pdf "\\NAS\Share\BU\File_PDF_BU_%ldt%.pdf"
:: archive older than the last one - remotely
pushd "A:\"
echo :: Move these files ::
echo ------------------------
for /f "skip=2 eol=: delims=" %%F in ('dir /b /o-d *.pdf') do MOVE "%%F" "A:\archive"
:: delete old archives - remotely
echo :: Delete these files ::
echo ------------------------
pushd "A:\archive"
for /f "skip=46 eol=: delims=" %%b in ('dir /a-d /o-d /b /s *.pdf') do del "%%b"
:: send confirmation email
"C:\Program Files\sendEmail\sendEmail.exe" -o -f "FromServer" -t me@domain.ltd -a "\\NAS\Share\BU\File_PDF_BU_%ldt%.pdf" -s smtp.domain.ltd:25 -u "Subject: %ldt%" -m Script successfully run"
:: wait 60 seconds
TIMEOUT /T 60
:: delete the old mapping
NET USE A: /DELETE /Y
:: exit the script
exit
At the moment, I am having issues with the files being generated from the programme itself. I am receiving two files Database01_YYYYMMDD-HHMMSSUUUU.pdf
and Database02_YYYYMMDD-HHMMSSUUUU.pdf
in the C:\Users\Administrator\Documents\My Database Backups
folder. So when I am copying, there is no way to limit to the two PDFs.
Is there a way to move the current two files in the root folder into a folder, then move that into the archive
folder. Then keep the most recent 11 folders (runs for 12 hours - 11 + 1 in root) in the archive folder. And attach the folder to the sendemail.exe
?