1

I have a BAT script which creates a file with data from a SQL stored procedure. What i would like to do is rename that file with a date/Time stamp but have not found a workable solution yet in google search.

example. current file name Pcnt.txt change it to PcntYYYYMMDDHHMM.csv, I am able to get the format to change to csv but the file is just renamed to Pcnt.csv and would need to add some code which will insert the date/time stamp.

Please help

thank you

4

2 回答 2

6

The first four lines of this code will give you reliable YY DD MM YYYY HH Min Sec variables in XP Pro and higher.

Use the ren command with the variables - see the help from REN /?

@echo off
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~2,2%" & set "YYYY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%" & set "Min=%dt:~10,2%" & set "Sec=%dt:~12,2%"

set "datestamp=%YYYY%%MM%%DD%" & set "timestamp=%HH%%Min%%Sec%"
set "fullstamp=%YYYY%-%MM%-%DD%_%HH%-%Min%-%Sec%"
echo datestamp: "%datestamp%"
echo timestamp: "%timestamp%"
echo fullstamp: "%fullstamp%"
pause
于 2013-11-07T11:43:41.937 回答
1
@echo off
    rem Prepare environment
    setlocal enableextensions

    rem Check arguments. First argument must be the file to rename
    if "%~1"=="" (
        echo Bad arguments
        goto endRename
    )
    if not exist "%~1" (
        echo File not found
        goto endRename
    )

    rem Get full path of file name
    set "_file=%~f1"

    rem Prepare filename for wmic query. Duplicate backslashes
    set "_file=%_file:\=\\%"

    rem Get datetime of file and rename it
    for /F "delims==. tokens=2" %%f in ('wmic path cim_datafile where name^='%_file%' get creationdate /value ^| findstr /i "CreationDate"') do (
        ren "%~f1" "%~n1_%%f%~x1"
    )

:endRename
    endlocal

If saved as timestamp.cmd call it as timestamp myFile.csv

于 2013-11-07T11:44:26.253 回答