Copy folders without files, files without folders, or everything using PowerShell Copy folders without files, files without folders, or everything using PowerShell powershell powershell

Copy folders without files, files without folders, or everything using PowerShell


Here are some ideas for handling each situation you describe.

Folder Structure Only

This will copy the source to a destination, recursing subdirectories but excluding all files.

robocopy $source $dest /e /xf *.*

Files Only (Flatten Structure)

There are a few ways to handle this, but I don't know of an especially good or elegant way. Here's an awkward but effective approach - for each subdirectory, it runs a non-recursive copy to a root destination folder. Criticism or nicer alternatives would be most welcome.

Get-ChildItem $source -Recurse |  Where-Object { $_.PSIsContainer -eq $true } |  Foreach-Object { robocopy $_.FullName $dest }

Everything

This scenario is the most straightforward of the bunch.

robocopy $source $dest /e

You can experiment with the switches yourself (referencing robocopy /? along the way) to fine tune the process. The trickiest scenario in my opinion is the one that flattens the directory structure. You'll have some decisions to make, like how you want to handle the same file name appearing in multiple directories.

As for how to accept options from the command line, I'd suggest putting together Powershell parameter sets for your three situations. There are a number of blog posts around that discuss the concept, but you can also see TechNet or run help about_Functions_Advanced_Parameters inside Powershell.


To copy everything in a folder hierarchie

Copy-Item $source $dest -Recurse -Force

To copy the hierarchie you can try:

$source = "C:\ProdData"$dest = "C:\TestData"Copy-Item $source $dest -Filter {PSIsContainer} -Recurse -Force

To flatten a file structure you can try:

$source = "C:\ProdData"$dest = "C:\TestData"New-Item $dest -type directoryGet-ChildItem $source -Recurse | `    Where-Object { $_.PSIsContainer -eq $False } | `    ForEach-Object {Copy-Item -Path $_.Fullname -Destination $dest -Force} 

Good luck!


I propose my solution :

$source = "C:\temp\"$dest = "C:\TestData\"#create destination directory if dont existNew-Item -ItemType Directory $dest -Force#To copy everything in a folder hierarchieGet-ChildItem $source -Recurse | Copy-Item -Destination {$_.FullName.Replace($source, $dest)}  -Force#To copy only directory hierarchie:Get-ChildItem $source -Recurse -directory | Copy-Item -Destination {$_.FullName.Replace($source, $dest)}  -Force#To copy only file (remove doublon be carefull):Get-ChildItem $source -Recurse -file | Copy-Item -Destination $dest -Force