【问题标题】: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' 
  }
}

请纠正我!

【问题讨论】:

  • 什么没有按预期工作?
  • 您尝试过 robocopy 吗?它是为。 ;-)

标签: 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'
      

      【讨论】:

        猜你喜欢
        • 2019-09-27
        • 1970-01-01
        • 2016-09-19
        • 2021-05-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-06
        相关资源
        最近更新 更多