Search code examples
windowspowershellcopycopy-item

How To copy only new files from one folder to another with PowerShell


I'm having a little trouble finishing a powershell script. I have a program that downloads images into a temporary folder, then within an hour it will delete the image files. Occasionally I would like to keep some of the files so I'm creating a powershell script to copy the image files out of the temporary folder to a new folder so that I can sort through them and keep what I want.

  • This is a one way copy from download folder to a destination folder.
  • Since the script will be ran every 20 minutes by the windows Task Scheduler, I want the script to compare the files it finds in the download folder to the files in the destination folder to see if it's already there.
  • If the file is new, then copy it, if it's already in the destination folder, ignore it.
  • This is purely matching filename only and not doing a binary compare.

Searching the web, I found a script on TomsITpro on "How To Sync Folders With PowerShell". This script copies the files both ways between two folders. As I try to modify this to copy only one way, I'm getting powershell errors.

$DownloadFolder = 'D:\TempImages'
$KeepFolder = 'D:\KeepImages'

$DownloadFiles = Get-ChildItem -Path $DownloadFolder
$KeepFiles = Get-ChildItem -Path $KeepFolder

$FileDiffs = Compare-Object -ReferenceObject $DownloadFiles -DifferenceObject $KeepFiles

$FileDiffs | foreach {
    $copyParams = @{
        'Path' = $_.InputObject.Fullname
    }
    if ($_.SideIndicator -eq '=>')
    {
        $copyParams.Destination = $KeepFolder
    }
    Copy-Item @copyParams
}

This script sort of works and does the compare very well and only copies new files if they already exist. The problem is when I run it from the d:\script folder, it copies all the files to the d:\script folder instead of the destination folder, D:\KeepImages. What am I doing wrong here?

Any help with this powershell script would be appreciated.


Solution

  • $DownloadFolder = 'D:\TempImages'
    $KeepFolder = 'D:\KeepImages'
    
    $DownloadFiles = Get-ChildItem -Path $DownloadFolder
    
    $KeepFiles = Get-ChildItem -Path $KeepFolder
    
    $FileDiffs = Compare-Object -ReferenceObject $DownloadFiles -DifferenceObject $KeepFiles
    
    $FileDiffs | foreach {
    $copyParams = @{
        'Path' = $_.InputObject.Fullname
               }
     $Downloadll = $copyParams.path
    if ($_.SideIndicator -eq '=>')
        {
          Copy-Item $Downloadll -Destination $KeepFolder 
        }
    }
    

    Try this