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?
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.