如何使用 PowerShell 仅将新文件从一个文件夹复制到另一个文件夹

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

我在完成 powershell 脚本时遇到了一些问题。我有一个程序可以将图像下载到一个临时文件夹中,然后在一小时内它会删除图像文件。有时我想保留一些文件,所以我创建了一个 powershell 脚本,将图像文件从临时文件夹复制到一个新文件夹,以便我可以对它们进行排序并保留我想要的。

通过网络搜索,我在 "How To Sync Folders With PowerShell" 上找到了 TomsITpro 上的脚本。此脚本在两个文件夹之间双向复制文件。当我尝试修改它以仅以一种方式复制时,我遇到了 powershell 错误。

$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
}

这个脚本可以正常工作,并且可以很好地进行比较,并且只复制已经存在的新文件。问题是当我从 d:\script 文件夹 运行 它时,它将所有文件复制到 d:\script 文件夹而不是目标文件夹 D:\KeepImages。我在这里做错了什么?

任何有关此 powershell 脚本的帮助将不胜感激。

尝试添加:Copy-Item -Force -Destination $KeepFolder

而不是Copy-Item @copyParams

$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 
    }
}

试试这个