1

I'm trying to tidy up imported files from my iPhone using a PowerShell script, specifically wanting edited photos (IMG_E001.jpg) to overwrite the non-edited photos (IMG_001.jpg).

I'm using the rename-item but can't figure out how to get it to overwrite the file. My current workaround is to move all of the edited files into their own folder, run the script, and then copy them over the top of the original files but this is a bit of a pain, plus it doesn't seem as reliable as a fully automated script.

Here's the code I'm using currently:

get-childitem -recurse -Include *.JPG | foreach { rename-item $_ $_.Name.Replace("E", "") };

Please can anyone help me to get this script to overwrite the existing files? Thank you

Nick
  • 3,745
  • 20
  • 56
  • 75
  • 3
    Try adding a `-Force` like so: `Get-Childitem -Recurse -Filter *.JPG | Foreach-Object -Process { Rename-Item -Path $_.FullName -NewName $_.Name.Replace("E", "") -Force }` – Abraham Zinala Mar 08 '21 at 23:03
  • If that didn't work you'll need to delete the non-edited files first and then rename. – Santiago Squarzon Mar 08 '21 at 23:33
  • 2
    This is not a PowerShell issue or feature. Windows does not allow you to rename a file an existing file of the same name. It's an OS operational filesystem boundary. Thus the two-step this you have encountered. There are ways to do it in a single step. – postanote Mar 09 '21 at 04:41
  • Thank you @AbrahamZinala , unfortunately that gave an `Rename-Item : Cannot create a file when that file already exists.` error so I think these guys are right that I need to move or remove the files first. – Nick Mar 09 '21 at 10:47

1 Answers1

2

This is a limitation of rename-item as @postanote mentioned in his comment this is because windows does not allow you to rename a file to an existing name. You will need to remove the other file first or overwrite it. Instead you can use move-item -force for essentially the same effect as it will perform the overwrite.

get-childitem -recurse -Include *.txt | foreach { Move-Item $_ $_.Name.Replace("E", "") -Force };

For more information; here is a related thread rename-item and override if filename exists

Zachary Fischer
  • 361
  • 2
  • 5