28

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
}
3
  • Please explain in more details what functionality you would like to have. Some practical examples would be a good start. Commented May 9, 2017 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. Commented May 9, 2017 at 11:02
  • in short, it does not copies the folder but copies the file in it. Commented May 9, 2017 at 11:04

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

6 Comments

can you edit my code add in it please cheers
$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 }
no it does work. i have added that line mate.
@greeline you don't need a loop - just use the code I provided.
According to the docs, Container is on by default: learn.microsoft.com/en-us/powershell/module/…
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.