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

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
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.
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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.
Bill PrewIT / Software Engineering ConsultantCommented:
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


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
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

LD16Author Commented:
Tested and it works!
Thank you again for your help.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.