Search code examples
batch-filecmdbatch-rename

How do we rename a file with the last day of previous month in Windows batch files?


I need to program a batch that renames an Excel file with the date of the last day of the previous month in DDMMYYY format. I have an example of code renaming using the current date.

ren example.xls example_%DATE:/=%.xls

Is there a method to do the same with the last day of the previous month?

Thank you in advance.


Solution

  • You can also get some help from powershell:

    @echo off
    for /F "delims=" %%i IN ('powershell.exe -Command "(Get-Date -Day 1 -Hour 0 -Minute 0 -Second 0).AddSeconds(-1).ToString('yyyy-MM-dd')"') DO (
       ren "example.xls" "%%i.xls"
    )
    

    The date format can be changed as per your needs at the end of the powershell string which is currently ("yyyy-MM-dd")