简体   繁体   中英

Windows batch: variables set inside a loop are ignored

I'm using the following code inside a Windows batch (*.bat) file to run several SQL queries:

set PSTR=QUERY1,QUERY2

for %%a in (%PSTR%) do (

  set START=%date%:%time%
  "C:\Program Files\PostgreSQL\9.4\bin\psql.exe" -f "D:\SQL\%%a.sql" -h localhost -p 5432 -U postgres db_tom
  set END=%date%:%time%
  echo %%a  DEB %DEB%  FIN %FIN% >> "D:\LOGS\log.txt"

The echo writes the following string inside the log.txt file:

QUERY1 START END
QUERY2 START END

The variables set inside the loop are ignored. Is there another way to write this batch in order to get start and end datetime written down?

setlocal enabledelayedexpansion
for %%a in ...(
 set start=!date!:!time!
 ...
 set end=!date!:!time!
 echo !start! !end!
)

please consult any of the hundreds of SO items about delayed expansion - the setlocal enabledelayedexpansion invokes a mode where !var! retrieves the run-time value not the parse-time value of the variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM