Domanda

I wrote the following batch to do the following steps:

  • Check if a file on a server is opened by another user
  • make a backup of the file
  • open the file

2>nul ( >>test.xlsx (call )) if %errorlevel% == 1 goto end

@echo off
rem get date, make if file name friendly
FOR /F "tokens=1-4 delims=/ " %%i in ('date/t') do set d=%%j-%%k-%%l@%%i@
rem get time, make if file name friendly
FOR /F "tokens=1-9 delims=:. " %%i in ('time/t') do set t=%%i_%%j_%%k%%l

set XLSX=%d%%t%.xlsx
ren Test.xlsx %xlsx%
xcopy *.xlsx J:\Test\Backup

ren %xlsx% Test.xlsx

call Test.xlsx

:end

The problem is, that the line wich tries to check if the file is locked does not work on the server.

Can anybody help me to find the mistake in my batch?

È stato utile?

Soluzione

If you write

2>nul ( >>test.xlsx (call )) if %errorlevel% == 1 goto end

you get an error. if is not expected. Two instructions in the same line without separation.

If it is converted into

2>nul ( >>test.xlsx (call )) & if %errorlevel% == 1 goto end

Then the problem is delayed expansion. The %errorlevel% variable is replaced with its value when the line is parsed and at this time, the first part of has not been executed, so no errorlevel is set.

If you change it to

2>nul ( >>test.xlsx (call )) 
if %errorlevel% == 1 goto end

it will work

For a more concise construct, you can try this

(>>test.xlsx call;) 2>nul || goto end

Same function, less code.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top