使用 powershell 复制新的和更新的文件

Using powershell to copy new and updated files

在 Powershell 方面,我完全是个新手,但我得到了一个需要改进的脚本,以便我们可以将更新文件或新文件从一台服务器移动到另一台服务器。我已经设法掌握了当前的脚本,但正在努力寻找正确的 cmdlet 和参数来实现所需的行为。

我的脚本成功地检测到更改的文件并将它们移动到准备好传输到另一台服务器的位置,但它没有检测到任何新文件。

任何人都可以指导我如何实现这两种行为吗?

$CurrentLocation = "C:\current"
$PreviousLocation = "C:\prev"
$DeltaLocation = "C:\delta"

$source = @{}

#
# Get the Current Location file information
#
Get-ChildItem -recurse $CurrentLocation | Foreach-Object {
    if ($_.PSIsContainer) { return }
    $source.Add($_.FullName.Replace($CurrentLocation, ""), $_.LastWriteTime.ToString())
}
Write-Host "Content of Source"
$source

$changesDelta = @{}
$changesPrevious = @{}

#
# Get the Previous Directory contents and compare the dates against the Current Directory contents 
#
Get-ChildItem -recurse $PreviousLocation | Foreach-Object {
    if ($_.PSIsContainer) { return }
    $File = $_.FullName.Replace($PreviousLocation, "")
    if ($source.ContainsKey($File)) {
        if ($source.Get_Item($File) -ne $_.LastWriteTime.ToString()) {
            $changesDelta.Add($CurrentLocation+$File, $DeltaLocation+$File)
            $changesPrevious.Add($CurrentLocation+$File, $PreviousLocation+$File)
        }
    }
}
Write-Host "Content of changesDelta:"
$changesDelta
Write-Host "Content of changesPrevious:"
$changesPrevious

#
# Copy the files into a temporary directory
#
foreach ($key in $changesDelta.Keys) {
    New-Item -ItemType File -Path $changesDelta.Get_Item($key) -Force
    Copy-Item $key $changesDelta.Get_Item($key) -Force
}
Write-Host $changesDelta.Count "Files copied to" $DeltaLocation

#
# Copy the files into the Previous Location to match the Current Location
#
foreach ($key in $changesPrevious.Keys) {
    Copy-Item $key $changesDelta.Get_Item($key) -Force
}

这是满足您需求的简化方法。需要注意的一件事是,我使用的一些构造需要 PSv3+。这不是复制目录结构,只是复制文件。此外,它比较可能会或可能不会做您想要的基本名称(忽略扩展名)。它可以通过使用 .Name 而不是 .BaseName

来扩展以包括扩展
#requires -Version 3

$CurrentLocation  = 'C:\current'
$PreviousLocation = 'C:\prev'
$DeltaLocation    = 'C:\delta'

$Current  = Get-ChildItem -LiteralPath $CurrentLocation -Recurse -File
$Previous = Get-ChildItem -LiteralPath $PreviousLocation -Recurse -File

ForEach ($File in $Current)
{
    If ($File.BaseName -in $Previous.BaseName)
    {
        If ($File.LastWriteTime -gt ($Previous | Where-Object { $_.BaseName -eq $File.BaseName }).LastWriteTime)
        {
            Write-Output "File has been updated: $($File.FullName)"
            Copy-Item -LiteralPath $File.FullName -Destination $DeltaLocation
        }
    }
    Else
    {
        Write-Output "New file detected: $($File.FullName)"
        Copy-Item -LiteralPath $File.FullName -Destination $DeltaLocation
    }
}

Copy-Item -Path "$DeltaLocation\*" -Destination $PreviousLocation -Force