0

I want to change the extension of a few files from .cap to .zip. I wrote following code in powershell:

Copy-Item $sourceFileLocation\*.cap $Temp -Force

But what if the same files with .zip extension already exist? It gives the following error on the console:

Rename-Item : Cannot create a file when that file already exists.
At E:\ExtractHashId.ps1:32 char:23
+     dir $Temp\*.cap | Rename-Item -NewName{$_.Name -replace ".cap", ".zip"}
+                       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : WriteError: (C:\Users\v-kamo...News_Locals.cap:String) [Rename-Item], IOException
    + FullyQualifiedErrorId : RenameItemIOError,Microsoft.PowerShell.Commands.RenameItemCommand

So What I need to do to overwrite these files?

Spidy776
  • 181
  • 1
  • 2
  • 10
  • 3
    The error is from the Rename-Item cmdlet, your code example says copy-item. Could you clarify your existing code? – Trondh Feb 12 '15 at 06:30
  • You probably want [`Move-Item -Force`](http://stackoverflow.com/questions/21194093/rename-file-by-replacing-character-and-overwrite) – Mathias R. Jessen Feb 12 '15 at 09:23

1 Answers1

0
$SourceFile = "X:\Source\Folder\*.cap"
$Dest = "X:\Destination\Folder"
Get-ChildItem $SourceFile | Foreach {Copy-item $_ "$Dest\$($_.Name -replace ".cap", ".zip")" -Force}

Should give you the desired effect.

Problem lies in the fact that you want to rename the file after it has been moved or copied and while another file exists with the new name. This can't happen, you will get that error. What the above does is rename the file during transit. This means the file being written to the destination folder is the file with the new extension, so from here you can overwrite existing ones.

Ian
  • 16
  • 3