Comparing different file extension and copying files with PowerShell


Scenario: *.pdf in Folder1 *.rtf in Folder 2, both folders have the same file name but with different extensions. Need to Compare the two folders and copy over only the *.rtf that equal => from Folder2 to Folder3.


    Compare-Object (Get-childitem $Folder1 -Recurse | foreach-object {$_.basename}) (Get-childitem $Folder2 -Recurse | foreach-object {$_.basename})     -Property RelativePath, Name, Length |
Sort RelativePath, Name, Length -desc | % {
if ($file -ne $_.RelativePath)
{ $_ }
$file = $_.RelativePath
} | Where-Object {$_.SideIndicator -eq "=>"} | ForEach-Object {Copy-Item ("$Folder2\" + $file) -Destination ("$Folder3\" + $file) -Force}

Normally you should actually have a question. I'm not sure where you got the property RelativePath from so I present this which should be fairly easy to follow. I could have made this into a one line command but, again, this is more readable.

$Folder1 = "C:\temp\folder1"
$Folder2 = "C:\temp\folder2"
$Folder3 = "C:\temp\folder3"
$Folder1Contents = Get-childitem $Folder1 -Recurse -Include *.pdf
$Folder2Contents = Get-childitem $Folder2 -Recurse -Include *.rtf

Compare-Object $Folder1Contents $Folder2Contents -Property BaseName -PassThru | Where-Object{$_.SideIndicator -eq "=>"} | Move-Item -Destination $Folder3 -Force -WhatIf

Take the pdf files in $Folder1 and compare them to the rtf files in $Folder2. If there is a .rtf file in $Folder2 then it will be moved to $Folder3. -Force will overwrite and preexisting file in that directory so remove the -WhatIf once you are done testing.