Copy-Item inconsistent behavior?
Asked Answered
B

1

6

Consider this directory structure:

C:\temp\A\file.txt
C:\temp\B

If I run the command

Copy-Item "C:\temp\A" "C:\temp\B\A" -Recurse -Force -ErrorAction Stop

I have

C:\temp\A\file.txt
C:\temp\B\A\file.txt

If, starting from this new situation, I run the same command a second time, I end up with

C:\temp\A\file.txt
C:\temp\B\A\file.txt
C:\temp\B\A\A\file.txt

Why is the result different although I run the same command?

Bogosian answered 23/5, 2016 at 13:31 Comment(0)
P
4

In the first case the destination folder C:\temp\B\A doesn't exist, so Copy-Item creates the (missing) destination folder and copies the content of the source folder to it.

In the second case the destination folder already exists, so Copy-Item copies the entire source folder (including the folder itself) to the (existing) destination folder.

To avoid this behavior make sure the destination folder either does or does not exist before copying (depending on whether you want the source folder copied "to" the destination or "as" the destination). Use Test-Path to check for the existence of the destination and New-Item to create a missing folder.

Parenthood answered 23/5, 2016 at 14:47 Comment(1)
I came across this bug today as well (after having encountered it already a year ago...)Communicable

© 2022 - 2025 — McMap. All rights reserved.