Search code examples
powershellbatch-fileautomationfile-renamebatch-rename

Renaming multiple files depending on current name


Bit of a speculative question, I have several files that need renaming each day. I'm wondering if it's possible to re-name them to the required spec automatically using a .bat or otherwise simple script.

An example filename would be: OKS-SABB MT940 MT940-OKS2015-11-26-09.38.18.502511.940

What it would need to be changed to is: OKS-SABB [Date -1 day].940

so: OKS-SABB 2015-11-25.940 if today is the 26th.

The file names all conform to that format, except they have different prefixes. e.g

OKA-SABB MT940 MT940-OKS2015-11-26-09.38.18.502511.940

OKB-SABB MT940 MT940-OKS2015-11-26-09.38.18.502511.940

OKS-SABB MT940 MT940-OKS2015-11-26-09.38.18.502511.940

The prefixes need to be maintained in the name change.

Now, is this something possible/ practicable? If yes, how would I go about performing it?

Thanks for the help,


Solution

  • this should do the work. Normally, we don't just write code for people who don't try anything by themselves. But I have a good day, so why not.

    $Path = "C:\Install\test"
    $Date = ((Get-Date).AddDays("-1").ToString('yyyy-MM-dd'))
    $Files = gci $Path -Filter *.940 | ForEach {
        $Prefix = $_.Name.Split('-')[0]
        Rename-Item -Path $_.FullName -NewName "$Prefix-SABB-$Date.940"
    }
    

    Just copy this into a text-file and save it as RenameFiles.ps1 and make a scheduled task out of it or whatever you want.

    Change the Value of the $Path Variable to your Path.