1
votes

I am trying to move all folders/subfolders/subfiles from one folder on a server to another using a powershell script, while keeping the same file structure throughout. To do this I am using Get-childItem | copy-item. All folders, subfolders, and subfiles are moving properly EXCEPT for the first folder in the directory. It instead outputs all of these subfiles/subfolders from this folder into the destination. It does however keep their structure, just does not include their parent directory. My code is as follows:

Get-ChildItem $sourceFilePath -Force | Copy-Item -Destination ("*file path*" -f $destinationServer, $destinationClient) -Recurse -Force 
  • filepath is paraphrased to improve readability
  • $sourceFilePath is the source folder that I am trying to copy
  • $destination server / $destinationClient are variables used in the paraphrased "file path"

I cannot figure out why this code works for all other folders, subfolders, and files EXCEPT for this one single folder and its items. Any help would be greatly appreciated, and if there's any other information that would help please let me know.


Answer thanks to @Christian Müller:

New-Item $destinationFilePath -name "MissingFolder" -type directory -Force | Out-Null

Get-ChildItem $sourceFilePath -Force | Copy-Item -Destination ("*filepath*" -f $destinationServer, $destinationClient) -Recurse -Force

1

1 Answers

0
votes

This is a really strange bug and also astonished myself! :)

It seems when the destination base directory is not existing, than it is only created but not with content.

So with this construction, you can even debug this behaviour in ISE:

$sourceFilePath = "c:\temp\Test1"
$destPath = "c:\temp\Test2"
$a=Get-ChildItem $sourceFilePath -Force

rm -Force $destPath
foreach($x in $a) {
    $x | Copy-Item -Destination "$destPath" -Recurse -Force 
}

dir $destPath

Creating the target directory first, resolving the issue, with New-item:

$sourceFilePath = "c:\temp\Test1"
$destPath = "c:\temp\Test2"
$a=Get-ChildItem $sourceFilePath -Force

rm -Force $destPath

New-Item -ItemType Directory -Force -Path $destPath
foreach($x in $a) {
    $x | Copy-Item -Destination "$destPath" -Recurse -Force 
}

dir $destPath

But for my example it would work, to not using "Get-ChildItem" at all but

Copy-Item c:\temp\test1 -Destination c:\temp\test2 -Recurse -Force

Would this also work for you?

Copy-Item $sourceFilePath -Destination ("*file path*" -f $destinationServer, $destinationClient) -Recurse -Force