Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have folders with images (*.png and *.jpg)


And I want to rename all the files like this using powershell:

Folder1 - 01.png
Folder1 - 02.png
Folder1 - 03.jpg
Folder1 - 04.jpg
Folder1 - 05.png

So I came up with this simple line:

Get-ChildItem | Where-Object { $_.Extension -eq ".jpg" -or $_.Extension -eq ".png"} | rename-item -newname {$_.Directory.Name +" - " + $_.Name}

If I have 35 or less files in the folder, I will have the wanted result, but if there is 36 or more files, I will end up with this:

Folder1 - Folder1 - Folder1 - 01.png
Folder1 - Folder1 - Folder1 - 02.png
Folder1 - Folder1 - Folder1 - 03.jpg
Folder1 - Folder1 - Folder1 - 04.jpg
Folder1 - Folder1 - Folder1 - 05.png

The loop stops when the file's name exceeds 248 characters.

Any ideas why it's looping?

EDIT: As proposed, a simple solution is to check if the folder's name is already added to the file's name:

Get-ChildItem | Where-Object { $_.Extension -eq ".jpg" -or $_.Extension -eq ".png" -and !$_.Name.StartsWith($_.Directory.Name) } | rename-item -newname {$_.Directory.Name +" - " + $_.Name}

But it doesn't tell me why it's looping when there is over 36 files in the folder.

share|improve this question
up vote 0 down vote accepted

It would seem as if the rename looks like a new file to the loop and so it is being processed again.

Try putting in an additional test to the where to stop it looking at any file starting with "Folder 1".

share|improve this answer
I changed the code to check if the folder's name has already been added, but I still doesn't understand why this threshold of 36 make it loop. I will accept it as an answer if nobody come up with an explanation to this bug. – XST Jun 29 '13 at 3:31
I think that, if you were to dig deeper, it would probably be due to the size of the data. At some point, the script is probably overflowing an internal (system?) variable size and flushing to disk. At that point, you have "new" entries in the folder that the script duly processes. – Julian Knight Jun 29 '13 at 20:35

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .