powershellrename-item-cmdlet

Using the rename-item command to overwrite an existing file?


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


Solution

  • 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