r/PowerShell • u/Hack_Cubit • Jun 24 '26
Question Help: Appending Filenames Looping Repeatedly
Hi, folks, I've been running into this issue with some consistency. I'm hoping it's as simple as "I didn't put an escape clause in there" but I've had no luck understanding what I'm doing wrong.
I'm trying to rename files in bulk by simply adding a prefix to their filenames. Here's the command I used most recently, applied to a folder with 174 files:
Get-ChildItem -File | Rename-Item -NewName { "MYNEWPREFIX_" + $_.BaseName + $_.Extension }
In this example, the first 170 items were renamed, and the MYNEWPREFIX string was added multiple times (35 or 36 times, according to the individual files I verified). Over the past week or so, this command (and I think some other ones as well) have all yielded this result. Can someone point out to me what I'm doing wrong? Many things in advance!
16
u/surfingoldelephant Jun 24 '26
Get-ChildItemis re-discovering the files you've already renamed in that pipeline, so you end up with an endless renaming loop (at least untilMAX_PATHis reached). This and this comment has more info.You need to collect the files you want to rename upfront to avoid them being re-discovered. Something like this (
(...)forces accumulation):Or this:
Or if you use PowerShell v7, your code will work as-is since the issue only affects Windows PowerShell v5.1 or lower.
2
u/Qasimfa786 Jun 24 '26
the safer fix is to pull the items into memory first with Get-ChildItem | ... | Sort piped through nothing fancy, but explicitly snapshot to a variable:
2
u/jimb2 Jun 24 '26 edited Jun 24 '26
This will prevent prefix being added multiple times
I would tend to write this as a small script and dot run it.
Add some user feedback and maybe a pause for safety, eg
Using pipes is shorthand but it's opaque and dangerous. You really need to understand what's going on and get it right. A small script is a bit nicer to use.
1
u/Qasimfa786 Jun 24 '26
Fix: force the file list to be captured fully before any renaming starts:
1
u/Qasimfa786 Jun 24 '26
If you want to be extra safe; add a check like -NewName { if ($_.BaseName -notlike "MYNEWPREFIX_*") { "MYNEWPREFIX_" + $_.BaseName + $_.Extension } else { $_.Name } } as a belt-and-suspenders guard against double-prefixing.
0
u/Creative-Type9411 Jun 24 '26
What does Get-ChildItem -File do?