PowerShell - suppress Copy-Item 'Folder already exists' error
Asked Answered
C

3

33

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.
Cerulean answered 24/2, 2012 at 17:1 Comment(1)
Does adding -Force solve the problem?Vannessavanni
M
28

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 $_ } }
Monster answered 24/2, 2012 at 22:22 Comment(1)
Thank you, this works. Finally getting a chance to implement it and test today :)Cerulean
G
29

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
Gati answered 8/6, 2016 at 21:49 Comment(2)
Overwrite the existing folders? Or only overwrite files in the existing folders?Incoherent
I had to do both - -Recurse -Force- this one got me working.Shapely
M
28

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 $_ } }
Monster answered 24/2, 2012 at 22:22 Comment(1)
Thank you, this works. Finally getting a chance to implement it and test today :)Cerulean
E
13

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!

Eldreeda answered 24/2, 2012 at 17:58 Comment(1)
Yeah... that only sorta helps :) Is the already exists thing a bug in the Copy-Item cmdlet? Seems like a waste of output- if it's already there and I was about to create it then who cares.. at least give me a -slientOnExistingDirs or -verbose switch, right? Thanks for your help though.. I'll think about that option.Cerulean

© 2022 - 2024 — McMap. All rights reserved.