Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I am trying to find a script that will work in Windows and prefix all files in a folder with the containing folder name.

For example, in the folder C:\FolderName1 there are 3 files:

hello.jpg
test.txt
monday.docx

After the script has been run for the above files, the names will be as follows:

FolderName1 - hello.jpg
FolderName1 - test.txt
FolderName1 - monday.docx

I don't mind which scripting language this is in, but I haven't been able to find a solution anywhere.

Thanks in advance.

share|improve this question
add comment

2 Answers

How many folders are there? If just one, you may rename all files with single for loop:

  1. Create C:\FolderName1_out folder
  2. Open CMD prompt
  3. for %I in (C:\FolderName1\*) do echo rename "C:\FolderName1\%~nxI" "C:\FolderName1_out\FolderName1 - %~nxI"
  4. If rename plan seems right, remove echo from the command above and run again

If there are many folders, then you may create batch file (replace all % with %% and FolderName1 with %1) and run it multiple times, passing folder name as argument. You may even run that batch file in the for loop:

for /D %J in (*) do echo call my_batch.cmd %~nxJ

If output seems right, then remove echo and run again.

share|improve this answer
add comment

Using PowerShell. If you need to change file names only in one folder then use this:

gci c:\PathToFolder | Where {$_.psIsContainer -eq $false} | Rename-Item -NewName {$_.Directory.Name + " - " + $_.Name}

It changes all files in that folder (but excludes folders from renaming) to format PathToFolder - Filename

You can add -Recurse if you have nested folders:

gci c:\PathToParentFolder -Recurse | Where {$_.psIsContainer -eq $false} | Rename-Item -NewName {$_.Directory.Name + " - " + $_.Name}

Be sure to run on a test folder first or just add -WhatIf to the end of the command to see the potential results without actually destroying your data :)

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.