【问题标题】:PowerShell: Compare files in two different folderPowerShell:比较两个不同文件夹中的文件
【发布时间】:2020-09-07 09:49:38
【问题描述】:

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

$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. 文件未从源复制到目标

谁能帮帮我。 蒂亚!

【问题讨论】:

    标签: powershell copy compare


    【解决方案1】:

    对于 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))"}
    

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

    【讨论】:

    • 感谢您的支持。你能解释一下最后一部分吗?($_.substring(0,7))
    • 非常欢迎您!很抱歉没有澄清它:您可以忽略“-Destination”之后的最后一部分我只是想粘贴完整的代码,没有任何空白,它与您的要求无关。但是,如果您只是对它的作用感兴趣:“$_”表示“来自管道的每个元素”,而“substring(0,7)”将文件名从第 1 个字符剪切到第 7 个字符。我不得不将文件 123-123ABC.txt 复制到文件夹 123-123 中,因此目标文件夹只是文件名本身的一部分。
    猜你喜欢
    • 2012-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-12
    相关资源
    最近更新 更多