PowerShell:比较两个不同文件夹中的文件

PowerShell: Compare files in two different folder

我有一个源文件夹和一个目标文件夹。如果源文件夹中的文件比目标文件夹中的文件新,则必须替换它。 我自己尝试过,但它没有正常工作。代码可能对专业人士来说太复杂了。

$SourceAlarmgroups = $rootPath + "\..\..\..\..\..\..\Logical\VCShared\AlarmGroups"
$DestinationAlarmgroups = "$rootPath\Alarmgroups"

$lastModifiedDateSource = (Get-Item $SourceAlarmgroups).LastWriteTime
$lastModifiedDateDestination = (Get-Item $DestinationAlarmgroups).LastWriteTime

$FolderSource = Get-ChildItem -Recurse -Path $SourceAlarmgroups
$FolderDestination = Get-ChildItem -Recurse -Path $DestinationAlarmgroups

$FolderCheck = Compare-Object -ReferenceObject $FolderSource -DifferenceObject $FolderDestination

forEach($file in $FolderCheck){
    if ($file.sideindicator -eq "<="){
        $SetWriteCmd = 1
    }
}
if ($lastModifiedDateSource -gt $lastModifiedDateDestination -or $SetWriteCmd -eq 1 ){
    Write-Host " Collect alarm files..." 
    Get-ChildItem $SourceAlarmgroups -Include *.algrp | Copy-Item -Destination $DestinationAlarmGroups -Force -PassThru
    &$Script2RunAlarmexport
}else{ 
    Write-Host "Alarms: Already up to date"   
}

出现两个问题:

  1. 引用空文件夹不起作用,即如果目标文件夹为空,则会出错。
  2. 文件没有从源复制到目标

谁能帮帮我。 TIA!

对于 1.:

您需要检查您的文件夹是否为空:

$DestinationFolder= Get-ChildItem "DestinationFolder" | Measure-Object


if (-not($DestinationFolder.count -eq 0)) 
{
    "execute your code"
    break;
}

如果您知道要查找的路径或至少文件结尾(例如我使用的),您也可以使用 Test-Path

if ( Test-Path  "C:\Test") 
{
    Write-host "C:\Test already exists, either delete the directory or change to another directory in the code"
    break;
}

对于 2.:

即使在管道“Copy-Item”中也需要一个 -Path,而您的代码中没有。我有类似的情况,我通过以下方式解决了:

Get-ChildItem -Path C:\Test -File  -Name | ForEach-Object {Copy-item -Path "C:\Test$_"  -Destination  "C:\Test$($_.substring(0,7))"}

因此,您需要具体说明要从哪个路径复制,但是,您仍然可以让文件更加灵活。