How to convert date format in the filename using PowerShell or batch script
For example: abc_10072019.txt
to abc_20191007.txt
how to convert file name from abc_10072019.txt to abc_20191007.txt using power shell or batch script
Asked
Active
Viewed 79 times
-2

shabnam sm
- 5
- 2
-
1"I need" is not a question! Please take the [tour], visit the [help] and learn [ask] here! You will find out then that you will have to do some own efforts and that you need to share a [mcve] of those by [edit]ing your question... – aschipfl Dec 01 '19 at 10:31
3 Answers
0
The full batch script:(renames using current date)
@echo off
for /f "tokens=2,3,4 delims=/ " %%a in ('%date%') do (set date=%%a & set month=%%b & set year=%%c)
ren abc_10072019.txt abc_%year%%month%%date%.txt
goto :eof
-
I'm sorry, but I fail to see how your answer is relevant to the question asked. All that is required is to move the last four characters of the basename left by four characters. – Compo Dec 01 '19 at 12:26
-
-
The question was little unclear becuase it did not clearly tell about if it wants to change date formatting using current date or the date in the question. – Dec 01 '19 at 15:44
-
1
-
... crystal clear on the date thing. Not clear if it's just one file or more of them and if they are all in one folder or scattered in several subfolders. The question speaks about one file only, but the request for a script suggests there are a lot of files. – Stephan Dec 01 '19 at 19:07
-
Yes..its just one file in a specific path...and file has to be copied to another folder by renaming it ...by doing date conversion in a filename as specified above...how to do this using powershell – shabnam sm Dec 01 '19 at 19:36
0
@echo off
setlocal enabledelayedexpansion
break>abc_10072019.txt
for %%f in (*_*2019.txt) do (
for /f "tokens=1,* delims=_" %%a in ("%%~nf") do (
set "dat=%%b"
set "newdat=!dat:~4!!dat:~0,2!!dat:~2,2!
ECHO ren "%%f" "%%a_!newdat!%%~xf"
)
)
remove the ECHO
after verifying it does what you want.

Stephan
- 53,940
- 10
- 58
- 91
0
For a basic batch-file solution you could try:
@For /F "Delims=|" %%# In ('^""%__AppDir__%where.exe" .:*_????????.txt 2^>NUL^"')Do @Set "_=%%~n#"&Call Echo=Ren "%%#" "%%_:~,-8%%%%_:~-4%%%%_:~-8,4%%%%~x#"
If you're satisfied with the output, remove Echo=
to actually perform the rename.
Please note that no check is done to ensure that the last eight characters of the basename are a valid date string.
Here's a potential powershell option, which can be ran from a batch-file:
@"%__AppDir__%WindowsPowerShell\v1.0\powershell.exe" -NoP "GCI -Filt '*_????????.txt' -EA SilentlyContinue|?{!$_.PSIsContainer -And $_.Name -Match '_[\d]{8}\.txt$'}|%%{RnI $_.Name $([DateTime]::ParseExact($_.BaseName.Split('_')[-1],'MMddyyyy',$Null)).ToString('yyyyMMdd') -WI}"
If you're satisfied with the output, remove -WI
to actually perform the rename.

Compo
- 36,585
- 5
- 27
- 39