简体   繁体   中英

Windows batch file not outputting variables

I have a batch file to create weekly backups. I create a variable called mydate which I use to both format the output folder and to echo for the log. When I run the batch with each line redirected to the log file, it works fine:

set mydate=%date:~10,4%-%date:~4,2%-%date:~7,2%
echo My Date is %mydate% >>TestEchoLog.txt
echo Backup triggered at %mydate% >>TestEchoLog.txt

Cmd window:

D:\>set mydate=2017-06-26
D:\>echo My Date is 2017-06-26  1>>TestEchoLog.txt
D:\>echo Backup triggered at 2017-06-26   1>>TestEchoLog.txt

TestEchoLog.txt:

My Date is 2017-06-26 
Backup triggered at 2017-06-26

However, if I wrap the commands into a single redirect, my variables stop working:

>>TestEchoLog.txt (
set mydate=%date:~10,4%-%date:~4,2%-%date:~7,2%
echo My Date is %mydate% 
echo Backup triggered at %mydate% 

Cmd window:

D:\>(
set mydate=2017-06-26
 echo My Date is
 echo Backup triggered at
) 1>>TestEchoLog.txt

TestEchoLog.txt:

My Date is  
Backup triggered at  

How can I fix this? Obviously a workaround is to just have the redirect on every line, but it's a long enough instruction set that I'd rather not.

Thanks!

Set your variable before echoing it into the file :

set mydate=%date:~10,4%-%date:~4,2%-%date:~7,2%
(
echo My Date is %mydate% 
echo Backup triggered at %mydate%
)>>TestEchoLog.txt

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