问题
Sorry if this is a really simple process.
I've got a folder structure with ~4,000 directories at root level (empty), and another location with another set of folders with data.
I want to copy only the files from within the folders in location2 to the folders within location1 ie \FolderABC123\Archive, but only if the directory names match. I'm sure windows explorer copy, or xcopy or some other utility can do it with more ease, but I'd like to get my head into PowerShell, and think this would be a good start?
thank you. Chris
回答1:
# Fist, get a list of all target directories (i.e.: directories under $destination that have a match in $source)
$targetDirs = dir -Path $source -Recurse -Force |
?{ $_.psIsContainer } |
%{ $_.FullName -replace [regex]::Escape($source), $destination } |
%{ if (Test-Path $_) { $_ }}
# Then, enumerate all files from source and copy them only if the corresponding target dir exists
dir -Path $source -Recurse -Force |
?{ -not $_.psIsContainer } |
?{ Test-Path (Split-Path ($_.FullName -replace [regex]::Escape($source), $destination) -Parent) } |
copy -Force -Destination { $_.FullName -replace [regex]::Escape($source), $destination }
回答2:
You can use powershell.
Set the path in the beginning.
$strSouce = "Path"
$strDestination = "Path"
Then search foreach file in the source.
Foreach ($objFile in Get-ChildItem -Path $strSouce -Recurse | Where-Object -FilterScript {$_.PsIsCointainer -eq $false}) {]
Copy every item from the source to the destination. For the destination you have to replace the source path to the destiantion path.
Copy-Item -Path $objFile.FullName -Destination $objFile.FullName.Replace("$strSouce", "$strDestination")
For your learning, set the snippet to the correct place.
来源:https://stackoverflow.com/questions/25542608/noob-to-powershell-copying-files-within-folder