Copy-Item copies folder inside the target when running second time Copy-Item copies folder inside the target when running second time powershell powershell

Copy-Item copies folder inside the target when running second time


Seems like you want to copy the content of c:\Source. You just need to add \*:

Copy-Item -Path "C:\Source\*" -Destination "C:\Target" -Force -Recurse | Out-Null

It works for the first run because you delete the target folder and the cmdlet now copies the folder C:\Source to C:\Target. If C:\Targetexists, the cmdlet will copy the source into the Target folder.


Copy-Item has inconsistent behaviour based on the fact if the destination exist or not.

If you want to have a consistent copy experience, use this pattern:

$copyFrom = 'C:\Foo\Bar\TargetDirectoryToCopy'$destinationPath = 'D:\Bar\Foo\'$newItemParams = @{    Path        = $destinationPath    ItemType    = 'Directory'    Force       = $True}$copyParams = @{    Path        = $copyFrom    Destination = $destinationPath    Recurse     = $True    Confirm     = $false    Force       = $True}New-Item @newItemParamsCopy-Item @copyParams

Result

The directory D:\Bar\Foo\ will have TargetDirectoryToCopy directory nested inside.

So if there is a file C:\Foo\Bar\TargetDirectoryToCopy\FooBar.txt, its copy will be created as D:\Bar\Foo\TargetDirectoryToCopy\FooBar.txt along with any another file in C:\Foo\Bar\TargetDirectoryToCopy