Powershell Rename-Item repeats if the number of files is large

(I'm just going to post every path here. It feels awkwardly intimate but what harm could it possibly do, right?)

Here is my PowerShell command prompt:

PS D:\Local generations\Tlungvel> ls | Rename-Item -NewName {"TlungvelSolar " + $_.Name}
Rename-Item : Could not find a part of the path.
At line:1 char:6
+ ls | Rename-Item -NewName {"TlungvelSolar " + $_.Name}
+      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : WriteError: (D:\Local genera..._02.07.2021.xls:String) [Rename-Item], DirectoryNotFoundException
    + FullyQualifiedErrorId : RenameItemIOError,Microsoft.PowerShell.Commands.RenameItemCommand

Rename-Item : Could not find a part of the path.
At line:1 char:6
+ ls | Rename-Item -NewName {"TlungvelSolar " + $_.Name}
+      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : WriteError: (D:\Local genera..._23.07.2021.xls:String) [Rename-Item], DirectoryNotFoundException
    + FullyQualifiedErrorId : RenameItemIOError,Microsoft.PowerShell.Commands.RenameItemCommand

... and so on it goes for every file in the directory.

The command seem simple enough even for a beginner poweruser like me ("ls | Rename-Item -NewName {"TlungvelSolar " + $_.Name}") and it works fine if the number of files in the directory is small. But if the number of files reach a certain threshold the process just repeats itself indefinitely and throws itself into the above error for each file.

For example, one of the filenames is "Power_Drawal_from_23.07.2021___24.07.2021"

If the file count crosses 22 (for this filename) it renames it to "TlungvelSolar TlungvelSolar TlungvelSolar TlungvelSolar TlungvelSolar TlungvelSolar TlungvelSolar TlungvelSolar TlungvelSolar TlungvelSolar TlungvelSolar TlungvelSolar TlungvelSolar Power_Drawal_from_23.07.2021___24.07.2021" (the number of repetition is as limited by the Windows' maximum 256 character file path limit).

Now what I want it to rename it to is "TlungvelSolar Power_Drawal_from_23.07.2021___24.07.2021"

Again, it works fine if the number of files is less, and it also seem to depend on the filenames.


Solution 1:

your problem is caused by feeding items into the pipeline while changing the source. [grin] that makes it quite easy to re-process the same item - it LOOKS like a different item to the code.

the fix is something like one of the below solutions ...

  • grab all the items into a $Var and feed that complete collection into the pipeline
  • wrap the G-CI call in parens to force the call to grab everything one time
  • use a foreach loop

i prefer the 3rd of those since it makes for a much simpler, more obvious set of steps ... and thus easier to debug. [grin]