tobias2001
Goto Top

Batch: Check if for loop was successful

Hello,

I am currently trying to write a backup script in batch.

I have a folder called "backups" and a folder called "long-term-backups"

In the "backups" folder is a backup from the last 30 days.
In the "long-term-backups" folder is the backup from the 1. of each month.

The problem is that if the 1. of a month is on a weekend no backup is made and there is no backup to be moved to "long-term-backups".

So I decided to write a few lines to check if a backup from the current month already exists in the "long-term-backups" folder.

If there is none, the script should search the oldest backup in the "backups" folder from the current month.

My problem is, that I dont know how to check if my "for loop", searching the "long-term" folder was successful or not.

My code below.

FOR /f %%i IN ('dir /ad /o-d /b %BackupPfad%\Langzeitsicherungen\%aktuellesJahr%-%aktuellerMonat%-??') DO ( rem prüfen ob aktueller monat in langzeitsicherungen vorhanden ist  

	IF NOT %%i == %test% (
		echo Monat %aktuellerMonat% ist in Langzeitsicherungen
	)

	IF %%i == %test% (
		echo Monat %aktuellerMonat% nicht in Langzeitsicherungen
	)
)

%test% is an empty variable, I created to test if %%i is empty. It works if there is a backup, but if there is none I just get "File not found"

I would prefer to check if the for loop found something by using some kind of return value (like: 1 = found smth, 0 = found nothing).

I appreciate a little help.

Thank you in advance.

With kind regards
Tobias

Content-Key: 2084496185

Url: https://administrator.de/contentid/2084496185

Printed on: April 19, 2024 at 08:04 o'clock

Mitglied: 1915348599
Solution 1915348599 Mar 07, 2022, updated at Mar 08, 2022 at 09:58:19 (UTC)
Goto Top
I would prefer to check if the for loop found something by using some kind of return value (like: 1 = found smth, 0 = found nothing).
@echo off
set "found="  
FOR /f %%i IN ('dir /ad /o-d /b %BackupPfad%\Langzeitsicherungen\%aktuellesJahr%-%aktuellerMonat%-?? 2^>nul') DO set found=1  
if defined found (
    echo found
) else (
   echo not found
)