7

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?

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I came across this bug today as well (after having encountered it already a year ago...)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.