Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use PowerShell copy-item and keep structure

Tags:

powershell

I have a directory structure that looks like this:

C:\folderA\folderB\folderC\client1\f1\files C:\folderA\folderB\folderC\client1\f2\files C:\folderA\folderB\folderC\client2\f1\files C:\folderA\folderB\folderC\client2\f2\files C:\folderA\folderB\folderC\client3\f1\files C:\folderA\folderB\folderC\client4\f2\files 

I want to copy the content of the f1 folders in C:\tmp\ to get this

C:\tmp\client1\f1\files C:\tmp\client2\f1\files C:\tmp\client3\f1\files 

I tried this:

Copy-Item -recur -path: "*/f1/" -destination: C:\tmp\ 

But it copies the contents without copying the structure correctly.

like image 962
Sylvain Avatar asked Mar 25 '11 12:03

Sylvain


People also ask

Does copy-item overwrite?

The Copy-Item cmdlet has the Container parameter set to $false . This causes the contents of the source folder to be copied but doesn't preserve the folder structure. Notice that files with the same name are overwritten in the destination folder.

How do you copy an entire directory structure?

Use the cp command to create a copy of the contents of the file or directory specified by the SourceFile or SourceDirectory parameters into the file or directory specified by the TargetFile or TargetDirectory parameters.


2 Answers

In PowerShell version 3.0 and newer this is simply done this way:

Get-ChildItem -Path $sourceDir | Copy-Item -Destination $targetDir -Recurse -Container 

Reference: Get-ChildItem

like image 169
Thomas M Avatar answered Sep 19 '22 00:09

Thomas M


PowerShell:

$sourceDir = 'c:\folderA\folderB\folderC\client1\f1' $targetDir = ' c:\tmp\'  Get-ChildItem $sourceDir -filter "*" -recurse | `     foreach{         $targetFile = $targetDir + $_.FullName.SubString($sourceDir.Length);         New-Item -ItemType File -Path $targetFile -Force;         Copy-Item $_.FullName -destination $targetFile     } 

Note:

  • The -filter "*" does not do anything. It is just here to illustrate if you want to copy some specific files. E.g. all *.config files.
  • Still have to call a New-Item with -Force to actually create the folder structure.
like image 42
Sentient Avatar answered Sep 19 '22 00:09

Sentient