I'd like to batch rename files in a folder, prefixing the folder's name into the new names. i.e. files in C:\house chores\ will all be renamed house chores - $old_name.
I'd like to batch rename files in a folder, prefixing the folder's name into the new names. i.e. files in C:\house chores\ will all be renamed house chores - $old_name.
I was tearing my hair out because for some items, the renamed item would get renamed again (repeatedly, unless max file name length was reached). This was happening both for Get-ChildItem and piping the output of dir. I guess that the renamed files got picked up because of a change in the alphabetical ordering. I solved this problem in the following way:
Get-ChildItem -Path . -OutVariable dirs
foreach ($i in $dirs) { Rename-Item $i.name ("<MY_PREFIX>"+$i.name) }
This "locks" the results returned by Get-ChildItem in the variable $dirs and you can iterate over it without fear that ordering will change or other funny business will happen.
Dave.Gugg's tip for using -Exclude should also solve this problem, but this is a different approach; perhaps if the files being renamed already contain the pattern used in the prefix.
(Disclaimer: I'm very much a PowerShell n00b.)
Based on @ofer.sheffer answer, this is the CMD variant for adding an affix (this is not the question, but this page is still the #1 google result if you search affix). It is a bit different because of the extension.
for %a in (*.*) do ren "%~a" "%~na-affix%~xa"
You can change the "-affix" part.
For anyone using PowerShell with this same requirement (adding a prefix to a file name in a directory), you will likely find that if you use some form of...
Get-ChildItem ./ | Rename-Item -NewName {"prefix" + $_.Name}
...that the files will continually get the prefix added in a loop until the windows file name length limit is reached. So instead of "prefixFile1.txt" you get: "prefixprefixprefixprefixprefixprefix...File1.txt". The cause of this is Get-ChildItem cmdlet will continually pipe the newly named file back into the Rename-Item cmdlet.
Solution for this isn't too bad, just make use of PowerShell's subexpression operator.
$(Get-ChildItem ./) | Rename-Item -NewName {"prefix" + $_.Name}
Putting $() around a Get-ChildItem ensures that all of the currently existing files get returned first and are then piped into Rename-Item, rather than piped in dynamically without the subexpression operator. Just keep in mind if you have millions+ files/items as it may take awhile to iterate all of them before any renames are carried out.