Prefix files with the current directory name using Powershell

Posted by XST on Super User See other posts from Super User or by XST
Published on 2013-06-28T03:11:36Z Indexed on 2013/06/28 4:23 UTC
Read the original article Hit count: 523

Filed under:
|

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

>C:\Directory\Folder1
01.png
02.png
03.jpg
04.jpg
05.png

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

>C:\Directory\Folder1
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:

>C:\Directory\Folder1
Folder1Folder1Folder1 - 01.png
Folder1Folder1Folder1 - 02.png
Folder1Folder1Folder1 - 03.jpg
Folder1Folder1Folder1 - 04.jpg
Folder1Folder1Folder1 - 05.png

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

Any ideas why it's looping?

© Super User or respective owner

Related posts about Windows

Related posts about powershell