I’m trying to add a prefix to every file in a folder with PowerShell, but some files end up with the prefix repeated many times and the command seems to keep running. What’s causing that, and how can I avoid it?
Why does my filename prefix keep getting added over and over?
Answers
The key issue is piping a live file listing straight into a rename operation. As names change, the listing can encounter renamed files again, so the prefix gets added repeatedly. Take a snapshot of the files first, then rename that fixed set.
For example: $files = Get-ChildItem -File; $files | Rename-Item -NewName { 'MYNEWPREFIX_' + $_.Name }. Try it on a copy of a small folder before running it on the originals.
Reply to this answer
Also add a guard so files that already have the prefix are skipped. That makes rerunning the script much safer:
Get-ChildItem -File | Where-Object { $_.Name -notlike 'MYNEWPREFIX_*' } | Rename-Item -NewName { 'MYNEWPREFIX_' + $_.Name }
-File just filters the results to files rather than directories. It doesn’t write a list to a text file.
Reply to this answer
Do a dry run before changing anything. Rename-Item has a -WhatIf option, which shows the planned renames without applying them. Once the output looks right, remove -WhatIf.
And consider using $_ .Name rather than joining BaseName and Extension. The space in that example should be removed in actual PowerShell syntax, but Name is simpler when you want to preserve the full filename.
Reply to this answer
Add your answer
Answers are reviewed before publication.
Related Discussions