0

I have a folder full of files, let's call it folder A, some of which (but not all) are also present in another folder, called folder B.

The files in B are out of date, and I would like to copy the newer versions of those files from A to B (overwrite the ones in B), but not copy all of the extra files from A which do not already exist in B.

There may also be files in B that are not in A.

Is there a way to do this with powershell? I know I can probably do it with xcopy, as in this question but I am looking for a pure Powershell solution.

I do not care if the files are newer, older or unchanged etc.

nik
  • 726
  • 2
  • 12
  • 28

1 Answers1

1

This is relatively straightforward by looping through the files in A and checking if they're in B.

$aDir = "C:\Temp\powershell\a"
$bDir = "C:\Temp\powershell\b"

$aFiles = Get-ChildItem -Path "$aDir"
ForEach ($file in $aFiles) {
    if(Test-Path $bDir\$file) {
        Write-Output "$file exists in $bDir. Copying."
        Copy-Item $aDir\$file $bDir
    } else {
        Write-Output "$file does not exist in $bDir."
    }
}
Alec Collier
  • 1,483
  • 8
  • 9
  • Shouldn't it better be `if (Test-Path (Join-Path $bDir $file.Name))` and what about copy if newer? –  Aug 11 '17 at 07:43