Home > Net >  How to batch rename folders by the name of the first file in it with a specific extension
How to batch rename folders by the name of the first file in it with a specific extension

Time:09-16

i have a couple of thousand folders with a not human readable name (random number). I would like to batch rename the folder name after the first file-name with a .3ds extension which is in every folder.

How can i do that? Iam on a Windows System. So batch or powershell?

CodePudding user response:

Give this a try. I've added the -WhatIf switch to the rename-item command so you can test the code. Remove it when you are ready to actually rename folders.

# Get folders to be renamed
$Folders = Get-ChildItem -Path "C:\Path\To\Main\Folder" -Directory

# Loop over each folder
foreach ($Folder in $Folders) {
   # Get the .3ds file inside
   $File = Get-ChildItem -Path $Folder.Fullname -Filter "*.3ds" | Sort-Object -Property Name | Select-Object -First 1

   # Rename the folder (-WhatIf added so you can test. Remove it when you're ready to rename)
   Rename-Item -Path $Folder.Fullname -NewName $File.Basename -WhatIf
}

CodePudding user response:

I also found this useful for using a bat file:

for /d %%a in (*) do (
  for %%b in ("%%a\*.3ds") do (
  ren "%%a" "%%~nb"
  )
)     
  • Related