Wayno
Wayno

Reputation: 1

Windows batch variable in for-loop

I created a quick batch file to check on valheim server and do backup of the save as it's not in the server folder, but i want to make it easier with variables.

would like to set a variable here for %%a in (C:\Users\Administrator\AppData\LocalLow\IronGate\Valheim\worlds\Dedicated.db)

eg for %%a in (%%valserverdb\Dedicated.db)

How can this can be done?

@echo off
:loop
tasklist /FI "IMAGENAME eq valheim_server.exe" 2>NUL | find /I /N "valheim_server.exe">NUL
if "%ERRORLEVEL%"=="0" echo Valheim Server is running
if "%ERRORLEVEL%"=="1" echo Valheim Server is not running starting it. | E:\gameservers\valheim\start_headless_server.bat

SET valserverdb=C:\Users\Administrator\AppData\LocalLow\IronGate\Valheim\worlds
SET valbackup=E:\gameservers\backup\IronGate\Valheim\worlds

for %%a in (C:\Users\Administrator\AppData\LocalLow\IronGate\Valheim\worlds\Dedicated.db) do set valserverdbcheck=%%~ta

for %%b in (E:\gameservers\backup\IronGate\Valheim\worlds\Dedicated.db) do set valbackupcheck=%%~tb

if "%valserverdbcheck%" gtr "%valbackupcheck%" (xcopy "%valserverdb%" "%valbackup%" /S /E /Y) else (@echo File has not been changed. skipping)

timeout /t 300 /nobreak > NUL
goto loop

Upvotes: 0

Views: 109

Answers (1)

Magoo
Magoo

Reputation: 79982

if "%ERRORLEVEL%"=="1" echo Valheim Server is not running starting it. | E:\gameservers\valheim\start_headless_server.bat

This runs E:\game...rver.bat and provides Valheim Server is not running starting it. as input on stdin to that .bat.

I'd suggest you replace | with & to execute both the echo and run the .bat.

--

Tips : Use set "var1=data" for setting values - this avoids problems caused by trailing spaces. In comparisons, use if "thing1" == "thing2" ... to avoid problems caused by spaces in thing1/2.

if "%valserverdbcheck%" gtr "%valbackupcheck%" compares the two dates a strings, not as date-values. I use dd/mm/yy... format for date, so for me, if the server date was 01/02/2021 (Feb 1st) and the backup date was 31/01/2021 then since "01/02/2021" is less than "31/01/2021" the comparison would not choose the appropriate option. I'd suggest neq would be a more appropriate comparison-operator.

%%a in (%%valserverdb\Dedicated.db) is incorrect syntax. Please provide examples of the what the prior and desired strings are.

Upvotes: 1

Related Questions