【问题标题】:powershell - Replace only old files with new files in destination directorypowershell - 仅用目标目录中的新文件替换旧文件
【发布时间】:2020-12-06 02:33:09
【问题描述】:
大家好,
我希望只用新文件替换旧文件
我试过了
Set-Location C:\contains_newfolder_contents\Old Folder
Get-ChildItem | ForEach-Object {
if ((Test-Path 'C:\contains_newfolder_contents\Sample Folder\$_' ) -and
(.$_.LastWriteTime -gt C:\contains_newfolder_contents\Sample Folder\$_.LastWriteTime' )) {
Copy-Item .\$_ -destination 'C:\contains_newfolder_contents\Sample Folder'
}
}
请纠正我!
【问题讨论】:
标签:
powershell
replace
directory
copy-item
【解决方案1】:
我建议您不要对源进行多次读取,而是创建一个查找表,然后这些简单的命令将达到预期的结果。
$source = 'C:\temp\Source'
$destintation = 'C:\temp\Destination'
$lookup = Get-ChildItem $destintation | Group-Object -Property name -AsHashTable
Get-ChildItem -Path $source |
Where-Object {$_.lastwritetime -gt $lookup[$_.name].lastwritetime} |
Copy-Item -Destination $destintation
【解决方案2】:
这是一个单行解决方案。我使用不同的文件夹名称使示例更易于阅读。
Get-ChildItem C:\temp\destination|foreach-object {$sourceItem = (get-item "c:\temp\source\$($_.name)" -erroraction ignore); if ($sourceItem -and $sourceItem.LastWriteTime -gt $_.lastwritetime) {Copy-Item -path $sourceItem -dest $_.fullname -verbose}}
对于每个现有文件,它会在源文件夹中找到匹配的文件。如果没有匹配的源项,$sourceItem 将为空。如果源日期较新,它会继续比较日期并复制。
【解决方案3】:
你也可以:
Get-ChildItem "C:\contains_newfolder_contents\Old Folder" -file | sort LastWriteTime -Descending | select -First 1 | Copy-Item -Destination 'C:\contains_newfolder_contents\Sample Folder'