How to copy a folder with subfolders?
This script works great in PowerShell. It copies all files of a specific type. But I want to copy files with its folders and 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
source to share
1 answer
PowerTip: use PowerShell to copy items and preserve folder structure
Q: How can I use Windows PowerShell 3.0 to copy the folder structure from disk to a network share and keep the original structure?
Answer: Use a cmdlet Copy-Item
and specify the switch parameter โContainer
:
$sourceRoot = "C:\temp"
$destinationRoot = "C:\n"
Copy-Item -Path $sourceRoot -Filter "*.txt" -Recurse -Destination $destinationRoot -Container
+21
source to share