Sunday, November 24, 2013

Recursively search and replace files from one folder into another

  1. $filter = '*.dll', '*.pdb'
  2. $copied = 0; $skipped = 0; $failed = 0
  3. $sourceFiles = $filter | % { Get-ChildItem $sourceDir -Filter $_ -Recurse } `
  4. | sort @{expression={$_.FullName.Length}} -Descending `
  5. | group Name -AsHashTable
  6. $targetFiles = $filter | % { Get-ChildItem $targetDir -Filter $_ -Recurse } `
  7. | ? { $sourceFiles.ContainsKey($_.Name) } `
  8. | sort FullName
  9. $targetFiles | % {
  10. $target = $_
  11. $sourceFiles[$target.Name] | % {
  12. $source = $_
  13. if ($target.FullName.EndsWith($source.FullName.Substring($sourceDir.Length),
  14. 'InvariantCultureIgnoreCase')) {
  15. if ($target.LastWriteTime.AddSeconds(2) -lt $source.LastWriteTime) {
  16. Write-Host $target.FullName
  17. try {
  18. Copy-Item $source.FullName $target.FullName -Force
  19. $copied++
  20. }
  21. catch {
  22. Write-Error $_.Message
  23. $failed++
  24. }
  25. }
  26. else {
  27. $skipped++
  28. }
  29. return
  30. }
  31. }
  32. }
  33. Write-Host "$copied copied, $skipped skipped, $failed failed in $($watch.Elapsed)"

No comments: