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

user1161625 picture user1161625 · Feb 24, 2012 · Viewed 29.4k times · Source

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.

Answer

Daniel Richnak picture Daniel Richnak · Feb 24, 2012

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 $_ } }