Powershell/Windows Batch/VB Script: rename files with folder name

Luis Diaz
Luis Diaz used Ask the Experts™
on
Hello experts,

I am looking for a batch, powershell or vbscript to cover the following requirement:

Loop a reported folder (no drill down needed):
-Rename the various files with reported folder name and add a numbering based on modified date from oldest to newest
-Example:
BaseDir= “C:\toto” contains filea.csv filea.xls fileb.csv
Expected result is the following:
toto-1.csv, toto-2.xls, toto-3.csv

If you have questions, please contact me.
Thank you.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
This is in test mode and will only display which files it would rename how. Remove the -WhatIf at the end to run it for real.
$baseDir = 'C:\toto'
$Script:i = 1
Get-ChildItem -Path $baseDir -File |
	Sort-Object -Property LastWriteTime |
	Rename-Item -NewName {"$([IO.Path]::GetFileName($_.DirectoryName))-$(($Script:i++))$($_.Extension)"} -WhatIf

Open in new window

Edit: Fixed issue with lost extension.
Test your restores, not your backups...
Top Expert 2016
Commented:
Here is a BAT script that should get the job done.

@echo off
setlocal EnableDelayedExpansion

set BaseDir=B:\EE\EE29144985\toto
set Count=0

for %%A in ("%BaseDir%") do set FolderName=%%~nA

for /f "tokens=*" %%A in ('dir /b /od /a-d "%BaseDir%\*.*"') do (
    set /a Count+=1
    ren "%BaseDir%\%%~A" "%FolderName%-!Count!%%~xA"
)

Open in new window


»bp
Most Valuable Expert 2018
Distinguished Expert 2018
Commented:
On a side note: if this is a one-time job, you can squeeze it all into a single line; as before, in test mode:
$Script:i=1; gci 'C:\toto' -File | sort LastWriteTime | ren -NewName {"$([IO.Path]::GetFileName($_.DirectoryName))-$(($Script:i++))$($_.Extension)"} -WhatIf

Open in new window

Luis DiazIT consultant

Author

Commented:
Tested and it works!
Thank you again for your help.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial