powershellrename-item-cmdlet

Powershell command that only works properly for a few files


I have a bunch of files named 001.jpg, 002.jpg and so on. I'd like to rename them Gym Heroes - 001 (US).jpg, etc. I wrote this Powershell command:

dir | Rename-Item -NewName { "Gym Heroes - " + $_.name.Insert(3," (US)") }

This works as expected when there are 35 or fewer pictures, but starting from 36 pictures, all the pictures are weirdly renamed (Gym Heroes - Gym (US) Heroes - Gym (US) Heroes - Gym (US) Heroes - Gym (US) Heroes - Gym (US) Heroes - Gym (US) Heroes - Gym (US) Heroes - Gym (US) Heroes - Gym (US) Heroes - Gym (US) Heroes - Gym (US) Heroes - 016 (US).jpg) and I get the following error message for each file (not the exact error message since I translated it to English):

Rename-Item : Part of the access path is impossible to find.
At character Line:1 : 7
+ dir | Rename-Item -NewName { "Gym Heroes - " + $_.name.Insert(3," (US ...
+       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : WriteError: (D:\Downloads... - 062 (US).jpg:String) [Rename-Item], DirectoryNotFoundE
   xception
    + FullyQualifiedErrorId : RenameItemIOError,Microsoft.PowerShell.Commands.RenameItemCommande

I don't understand at all why this is happening... I could rename my pictures 35 by 35 but I'd like to understand why my command doesn't work properly.

Thanks!


Solution

  • You need to include your dir/gci command in parentheses to force it to evaulate first. Otherwise you can get some items that appear to be processed multiple times.

    So...

    (dir) | Rename-Item -NewName { "Gym Heroes - " + $_.name.Insert(3," (US)") }