I have a batch script for backing up databases. I echo the %time% that script starts and then the %time% it ends to a log file. Even though the script takes 5 minutes to backup our databases the end time is identical to the start time.
我有一个用于备份数据库的批处理脚本。我回显脚本启动的%time%,然后是结束日志文件的%time%。即使脚本需要5分钟来备份我们的数据库,结束时间也与开始时间相同。
@echo off
:: Credentials preconfigured for backup-operator
net use y: \\172.16.104.201\Backups
:: Date in format YYYY.MM.DD
set DATESTAMP=%DATE:~-4%.%DATE:~3,2%.%DATE:~0,2%
set LOCAL_DIR=F:\Backups\
set EXTERN_DIR=Y:\DB3\
:: Output all to txt
>"%LOCAL_DIR%SQLBackups-%DATESTAMP%.txt" (
echo.
echo ------------------------------------------------------------------------------
echo -- Starting SQL Backups %date% %time% --
echo ------------------------------------------------------------------------------
echo.
:: Backup and Copy loop
setlocal enabledelayedexpansion
for %%i in (
DB1
DB2
DB3
DB4 etc...
) do (
set DATABASENAME=%%i
set BACKUPFILENAME=!LOCAL_DIR!!DATABASENAME!-!DATESTAMP!.bak
echo.
echo ------------------------------------------------------------------------------
echo -- Backing Up Database !DATABASENAME! to local--
echo ------------------------------------------------------------------------------
echo.
sqlcmd -E -S DB3 -d master -Q "BACKUP DATABASE [!DATABASENAME!] TO DISK = '!BACKUPFILENAME!' WITH DESCRIPTION = 'Full backup [!DATABASENAME!]', CHECKSUM, INIT, COMPRESSION"
echo.
echo.
echo -- Copying !DATABASENAME! Backup to external--
robocopy !LOCAL_DIR! !EXTERN_DIR! !DATABASENAME!-!DATESTAMP!.bak
echo.
echo -- !DATABASENAME! End --
echo.
echo.
)
endlocal
:: Delete files older than -d days from local
forfiles -p %LOCAL_DIR% -s -m *.bak -d "-180" /C "cmd /c echo @path & del @path""
forfiles -p %LOCAL_DIR% -s -m *.txt -d "-180" /C "cmd /c echo @path & del @path""
echo.
echo.
echo -- Script Complete %date% %time% --
echo.
)
robocopy %LOCAL_DIR% %EXTERN_DIR% "SQLBackups-%DATESTAMP%.txt"
net use y: /delete
2 个解决方案
#1
You have to add Setlocal EnableDelayedExpansion
below @echo off
and access the time with !time!
instead of %time%
. That should be it.
您必须在@echo下面添加Setlocal EnableDelayedExpansion并使用!time访问时间!而不是%time%。那应该是它。
#2
Volatile variables are unreliable. Any program, user, or install can kill them. Use tried and true methods.
易变量变量不可靠。任何程序,用户或安装都可以杀死它们。使用经过验证的方法。
for /f "Delims=" %A in ('time /t') do Set MyTime=%A
For a way that will work on all computers.
对于适用于所有计算机的方式。
#1
You have to add Setlocal EnableDelayedExpansion
below @echo off
and access the time with !time!
instead of %time%
. That should be it.
您必须在@echo下面添加Setlocal EnableDelayedExpansion并使用!time访问时间!而不是%time%。那应该是它。
#2
Volatile variables are unreliable. Any program, user, or install can kill them. Use tried and true methods.
易变量变量不可靠。任何程序,用户或安装都可以杀死它们。使用经过验证的方法。
for /f "Delims=" %A in ('time /t') do Set MyTime=%A
For a way that will work on all computers.
对于适用于所有计算机的方式。