使用BAT脚本在文件名中插入日期/时间戳

时间:2013-11-07 09:49:12

标签: batch-file

我有一个BAT脚本,它使用SQL存储过程中的数据创建一个文件。我想要做的是用日期/时间戳重命名该文件,但在谷歌搜索中还没有找到可行的解决方案。

例子。当前文件名Pcnt.txt将其更改为PcntYYYYMMDDHHMM.csv,我可以将格式更改为csv,但该文件刚刚重命名为Pcnt.csv,需要添加一些代码来插入日期/时间戳。

请帮忙

谢谢

2 个答案:

答案 0 :(得分:6)

此代码的前四行将为您提供XP Pro及更高版本中可靠的YY DD MM YYYY HH Min Sec变量。

将ren命令与变量一起使用 - 请参阅 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

答案 1 :(得分: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

如果保存为timestamp.cmd,请将其称为timestamp myFile.csv

相关问题