Tsabsuav
Tsabsuav

Reputation: 21

Rename a file with the previous month using a batch script

I'd like to rename a file with the previous month + current year using a batch script. Please help!

For example: rename c:\Example.txt Example_MMYY.txt

Where MM = previous month and YY = current year or Example_0718.txt

Upvotes: 1

Views: 4113

Answers (3)

Squashman
Squashman

Reputation: 14290

If you are ok with calling out to Powershell to get the date you can simplify the code.

for /f "usebackq" %%G in (`powershell "(Get-Date).AddMonths(-1).ToString('MMyy')"`) do set "mmyy=%%G"
rename Example.txt Example_%mmyy%.txt

Upvotes: 0

Aacini
Aacini

Reputation: 67216

This problem could be solved in a very simple way:

@echo off
setlocal

for /F "tokens=1,3 delims=/" %%m in ("%date%") do (
   set /A "MM=1%%m-1, YY=%%n-!(MM-100), MM+=12*!(MM-100)"
)

ren Example.txt Example_%MM:~-2%%YY:~-2%.txt

This method assume that the format of %date% variable is MM/DD/YYYY. If is not, just change the numbers in the "tokens=1,3" option.

Upvotes: 1

npocmaka
npocmaka

Reputation: 57252

try this:

 :prevmonthren
setlocal

::argument value
::set "file=%~f1"

::hardcoded value
set "file=testfile.txt"

for %%# in ("%file%") do (
    set "ext=%%~x#"
    set "nam=%%~n#"
)

for /f %%# in ('wMIC Path Win32_LocalTime Get /Format:value') do @for /f %%@ in ("%%#") do @set %%@


set /a prev_month=month-1
if %prev_month% lss 10 set "prev_month=0%prev_month%"
if %month%==1 (
    set "prev_month=12"
    set /a year=year-1
)
set year=%year:~2%
ren %file% %nam%_%prev_month%%year%%ext%


endlocal

you can use hardcoded value for the file location or to uncomment the first line where the file location is set (and comment the second) in order to use command line arguments.

Upvotes: 1

Related Questions