为什么我的变量在delayedexpansion for loop中保持不变? (命令提示符/ cmd.exe)

时间:2015-03-26 17:28:19

标签: loops batch-file for-loop scripting command-prompt

为什么下面的delayedexpansion循环脚本中的变量不能保持设置?

setlocal enabledelayedexpansion
set DB_LIST=(DB1 DB2)
for %%i in %DB_LIST% do (

    set DATABASENAME=%%i
    echo -- Backing Up Database %DATABASENAME% -- 
    set DATESTAMP=%DATE:~-4%.%DATE:~3,2%.%DATE:~0,2%
    set BACKUPFILENAME=F:\Backups\ScheduledBackups\%DATABASENAME%-%DATESTAMP%.bak
    echo.
    sqlcmd -E -S LiveDB2 -d master -Q "BACKUP DATABASE [%DATABASENAME%] TO DISK = '%BACKUPFILENAME%' WITH DESCRIPTION = 'Full backup [%DATABASENAME%]', CHECKSUM, INIT, COMPRESSION, STATS"
)
endlocal
pause

我得到一个试图用BACKUP DATABASE DB1 TO DISK = ''

执行的命令

谢谢!

1 个答案:

答案 0 :(得分:2)

那是因为您尝试使用百分号而不是感叹号来扩展变量。启用延迟扩展时,必须始终在for循环内使用感叹号。

试试这个:

setlocal enabledelayedexpansion
set DB_LIST=(DB1 DB2) 
for %%i in %DB_LIST% do (

set DATABASENAME=%%i
echo -- Backing Up Database !DATABASENAME! -- 
set DATESTAMP=%DATE:~-4%.%DATE:~3,2%.%DATE:~0,2%
set BACKUPFILENAME=F:\Backups\ScheduledBackups\!DATABASENAME!-!DATESTAMP!.bak
echo.
sqlcmd -E -S LiveDB2 -d master -Q "BACKUP DATABASE [!DATABASENAME!] TO     DISK = '!BACKUPFILENAME!' WITH DESCRIPTION = 'Full backup [!DATABASENAME!]', 

CHECKSUM, INIT, COMPRESSION, STATS")
endlocal
pause