powershell-仅将旧文件替换为目标目录中的新文件

问题描述

enter image description here

大家好,

我希望只用新文件替换旧文件

我尝试过

Name,Email,Manager_Name

请纠正我!

解决方法

您也可以做到:

Get-ChildItem "C:\contains_newfolder_contents\Old Folder" -file | sort LastWriteTime -Descending | select -First 1 | Copy-Item -Destination 'C:\contains_newfolder_contents\Sample Folder'
,

这是单行解决方案。我使用了不同的文件夹名称,以使示例更易于阅读。

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

对于每个现有文件,它将在源文件夹中找到匹配的文件。如果没有匹配的源项目,$ sourcItem将为null。它会继续比较日期并在源日期较新时进行复制。

,

我建议您制作一个查找表,而不是对源代码进行多次读取,然后这些简单的命令将获得所需的结果。

$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