我有一个类似的文件结构:
我需要编写脚本来递归检查文件是否存在于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
重要点:
我快速而又肮脏的方法是将单个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
}
}
}