Search code examples
powershellcopy-item

PowerShell Copy-Item not copying all files


I have a strange issue with the Copy-Item in PowerShell. Below you see two almost identical lines of code, only the source and destination is different.

Copy-Item "A:\*" -Destination "B:\" -Recurse -Force -Verbose -Confirm:$false -ErrorAction SilentlyContinu
Start-Sleep 3
Copy-Item "B:\*" -Destination "D:\" -Recurse -Force -Verbose -Confirm:$false -ErrorAction SilentlyContinu

These lines are a part of a script. It first notes the date and creates a log file and then it clears the B and D drive. After that, it starts copying. The first one, the Copy-Item A:\ to B:\ works, it copies everything.

When PowerShell gets to the second one, it only copies a few folders and just skips over the remaining folders. It doesn't throw me an error or anything.

When I manually execute the second line, it works, but not when it's in a script.

What is wrong here?


Solution

  • I'd use robocopy for this, it's included in all modern versions of windows and is very powerful and can complete pretty much any copy function you want.

    ROBOCOPY /MIR <Source> <Target>
    

    /MIR is the mirror switch. It will both copy source to target and delete anything in target that isn't present in source. Leaving target as a mirror copy of source.

    You might also want to look into the /MT multi-thread switch to speed things up if the directories contain a large number of files.