29

This script works perfectly in PowerShell. It copies all files with specific type. But I want copy files with it folders & subfolders.

$dest  = "C:\example"
$files = Get-ChildItem -Path "C:\example" -Filter "*.msg" -Recurse

foreach ($file in $files) {
    $file_path = Join-Path -Path $dest -ChildPath $file.Name

    $i = 1

    while (Test-Path -Path $file_path) {
        $i++
        $file_path = Join-Path -Path $dest -ChildPath
        "$($file.BaseName)_$($i)$($file.Extension)"
    }

    Copy-Item -Path $file.FullName -Destination $file_path
}
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
gree line
  • 321
  • 1
  • 3
  • 4
  • Please explain in more details what functionality you would like to have. Some practical examples would be a good start. – vonPryz May 09 '17 at 10:57
  • hi for eg there are 1000 .txt files in folders. this successfully copies that but it does not that folder which contain that files. – gree line May 09 '17 at 11:02
  • in short, it does not copies the folder but copies the file in it. – gree line May 09 '17 at 11:04

1 Answers1

56

PowerTip: Use PowerShell to Copy Items and Retain Folder Structure

Source: https://blogs.technet.microsoft.com/heyscriptingguy/2013/07/04/powertip-use-powershell-to-copy-items-and-retain-folder-structure/

Question: How can I use Windows PowerShell 3.0 to copy a folder structure from a drive to a network share, and retain the original structure?

Answer: Use the Copy-Item cmdlet and specify the –Container switched parameter:

$sourceRoot = "C:\temp"
$destinationRoot = "C:\n"

Copy-Item -Path $sourceRoot -Filter "*.txt" -Recurse -Destination $destinationRoot -Container
Community
  • 1
  • 1
gvee
  • 16,732
  • 35
  • 50
  • can you edit my code add in it please cheers – gree line May 09 '17 at 11:06
  • $dest = "C:\n" Copy-Item -Path $sourceRoot -Filter "*.txt" -Recurse -Destination $destinationRoot -Container $files = Get-ChildItem -Path "C:\Admin Support" -Filter "*.msg" -Recurse ForEach ($file in $files) { $file_path = Join-Path -Path $dest -ChildPath $file.Name $i = 1 While (Test-Path -Path $file_path) { $i++ $file_path = Join-Path -Path $dest -ChildPath "$($file.BaseName)_$($i)$($file.Extension)" } Copy-Item -Path $file.FullName -Destination $file_path } – gree line May 09 '17 at 11:12
  • 2
    no it does work. i have added that line mate. – gree line May 09 '17 at 11:12
  • @greeline you don't need a loop - just use the code I provided. – gvee May 09 '17 at 12:13
  • oh sorry, thankyou so much. – gree line May 10 '17 at 14:13
  • 3
    According to the docs, `Container` is on by default: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/copy-item?view=powershell-6#optional-parameters – Ohad Schneider Oct 25 '18 at 12:40