Search code examples
batch-filebatch-rename

appending date with filename using batch scripts


I am trying to set a housekeeping for different type of file. PFB scenario.

I have below set of files in a network path(\NAS.domain.local\data\Arasan)

  • test.sql
  • test1.txt
  • test2.log

I am trying to rename the files as shown below and move the files to .\Archive\ directory

  • Test_15-12-2016_151428.sql
  • Test1_15-12-2016_151428.txt
  • Test_15-12-2016_151428.log

([Filename]_DD-MM-YYYY_HHMISS.[ext])

I have built the below batch script.

@echo ON
SET Log_Path=\\NAS.domain.local\data\Arasan
SET Script_Path=C:\Scripts

REM ###########################################REM
REM ## Do make any changes to the text below ##REM
REM ###########################################REM

cd %Script_Path%
pushd %Log_Path%
dir /b /a-d > %Script_Path%\list.txt
set HH=%TIME:~0,8%
for /F %%A in (%Script_Path%\list.txt) do (
    setlocal EnableExtensions EnableDelayedExpansion
    set ffname=%%A
    set "fname=%%~nA"
    set "fext=%%~xA"
    ren !ffname! !fname!_%DATE%_%TIME:~0,2%%TIME:~3,2%%TIME:~6,2%!fext!
endlocal
)
del %Script_Path%\list.txt
move *.* Archive\
popd
exit

Now my issue is it is working perfectly in my machine but when I transfer this to server and execute. It is throwing "The syntax of the command is incorrect." Error. And it is moving the files without renaming. As for as i know, file name and extension is not being assigned to the variable properly in below part

set ffname=%%A
 set "fname=%%~nA"
 set "fext=%%~xA"

Server OS: Windows server 2008 R2 Standard(SP1)

Can anyone please help me. Thanks a lot.


Solution

  • Here is the part of the code you should be using to get a consistent date and time output:

    For /F "Skip=1" %%A In ('WMIC OS GET LocalDateTime') Do For %%B In (%%~nA
    ) Do Set "DTS=%%B"
    Set "DTS=_%DTS:~6,2%-%DTS:~4,2%-%DTS:~,4%_%DTS:~-6%"
    Echo( [%DTS%]
    Pause
    

    Just incorporate this into the rest of your code…