微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决PowerShell:比较两个不同文件夹中的文件

我有一个文件夹和一个目标文件夹。如果源文件夹中的文件比目标文件夹中的文件新,则必须将其替换。 我自己尝试过,但是它没有按预期的方式工作。对于专业人员来说,代码可能太复杂了。

$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))"}

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。