Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell - suppress Copy-Item 'Folder already exists' error

When I run a recursive Copy-Item from a folder that has sub folders to a new folder that contains the same sub folders as the original, it throws an error when the subfolders already exist.

How can I suppress this because it is a false negative and can make true failures harder to see?

Example:

Copy-Item "C:\realFolder\*" "C:\realFolder_new" -recurse

Copy-Item : Item with specified name C:\realFolder_new\subFolder already exists.
like image 400
user1161625 Avatar asked Feb 24 '12 17:02

user1161625


3 Answers

You could try capturing any errors that happen, and then decide whether you care about it or not:

Copy-Item "C:\realFolder\*" "C:\realFolder_new" -recurse -ErrorVariable capturedErrors -ErrorAction SilentlyContinue
$capturedErrors | foreach-object { if ($_ -notmatch "already exists") { write-error $_ } }
like image 183
Daniel Richnak Avatar answered Nov 19 '22 06:11

Daniel Richnak


If you add -Force to your command it will overwrite the existing files and you won't see the error.

-Recurse will replace all items within each folder and all subfolders.

Copy-Item "C:\realFolder\*" "C:\realFolder_new" -Recurse -Force
like image 34
leemicw Avatar answered Nov 19 '22 06:11

leemicw


You can set the error handling behavior to ignore using:

Copy-Item "C:\realFolder\*" "C:\realFolder_new" -recurse -ErrorAction SilentlyContinue

However this will also suppress errors you did want to know about!

like image 11
Andy Arismendi Avatar answered Nov 19 '22 05:11

Andy Arismendi