通过目录中的子路径递归查找n个匹配文件

问题描述 投票:1回答:1

我有一个类似的文件结构:

  1. RootDir \
    • ADir
      • 1.xml
      • 2.xml
    • BDir
      • 1.xml
      • 2.xml
      • 3.xml
    • CDir
      • 2.xml
      • 3.xml

我需要编写脚本来递归检查文件是否存在于RootDir下的多个目录中,该文件路径与RootDir下一级的目录相同。

例如RootDir \ ADir \ 1.xml也存在于位置RootDir \ BDir \ 1.xml

下面的代码返回匹配条目的路径,尽管有-exclude开关,但它仍继续与iteself匹配

$rootCompare = "C:\Users\XXX\Documents\Compare\RootDir"
$rootItems = get-childitem -Path C:\Users\XXX\Documents\Compare\RootDir -Recurse
foreach ($i in $rootItems){
$dirItems = get-childitem $i -File -Recurse | ForEach-Object {
   $fullName = $_.fullName
   $baseName = $_.baseName
   $baseExt = $_.Extension
   Write-Host "fullname="$fullName
   if (Test-Path $rootCompare\*\$baseName$baseExt -Exclude $fullName) {
       $fileSearch = get-ChildItem -Path $rootCompare\*\$baseName$baseExt -Exclude "*$fullName*"
       Write-Host "searching for file: "$fullName
       Write-Host "file exists in another location: "$fileSearch
       }
   }
}

示例返回:

fullname= C:\Users\XXX\Documents\Compare\RootDir\CDir\3.xml
searching for file:  C:\Users\XXX\Documents\Compare\RootDir\CDir\3.xml
file exists in another location:  C:\Users\XXX\Documents\Compare\RootDir\ADir\3.xml 
C:\Users\XXX\Documents\Compare\RootDir\CDir\3.xml

1)如何调整排除条件以防止其与自身匹配?

2)此版本仅适用于RootDir之下的1级。如何适应RootDir以下的n个级别?

例如,RootDir \ ADir \ DDir \ 1.xml也应与RootDir \ BDir \ DDir \ 1.xml匹配,但不匹配RootDir \ ADir \ 1.xml

重要点:

  • 目录的编号,名称和路径是动态的,不能进行硬编码
powershell
1个回答
0
投票

我快速而又肮脏的方法是将单个Get-ChildItem -Recurse放入变量中。然后我可以遍历该变量两次。一次获取第一个对象列表,第二次与第一个对象列表进行比较。然后,在比较中,我们要匹配名称相同的地方,全名不匹配。

$rootCompare = "C:\Users\XXX\Documents\Compare\RootDir"
$rootItems = get-childitem -Path $rootCompare -Recurse

foreach ($i in $rootItems){
    foreach ($j in $rootItems){
        if($i.Name -eq $j.Name -and $i.fullName -ne $j.fullName)
        {
            Write-Host "file" $i.fullName
            Write-Host "also exists in another location: "$j.fullName
        }
     }
}
© www.soinside.com 2019 - 2024. All rights reserved.