简体   繁体   中英

powershell - Replace only old files with new files in destination directory

在此处输入图像描述

Hello All,

I wish to replace only the old file with new file

I tried

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

Kindly correct me!

you can do it too:

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

Here's a one-line solution. I used different folder names to make the example easier to read.

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

For each existing file, it finds the matching file in the source folder. $sourcItem will be null if there is no matching source item. It proceeds to compare the dates and copy if the source date is newer.

Instead of making several reads to the source, I propose you make a lookup table and then these simple commands will achieve the desired results.

$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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM