This question already has an answer here:
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
}
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
来源:https://stackoverflow.com/questions/43867840/how-to-copy-folder-with-subfolders