在 Powershell 中查找重复的文件名

男人

我是 PowerShell 菜鸟,正在寻找一种在目录中查找重复文件并将文件的文件路径写入文本文件或 csv 文件的方法。我当前的代码正在运行,但效率极低且速度缓慢。任何建议将不胜感激

#Declaring the Array to store file paths and names
$arr = (get-childitem "My Path" -recurse | where {$_.extension -like '*.*'})

#creating an array to hold already found duplicate elements in order to skip over them in the iteration
$arrDupNum = -1

#Declaring for loop to itterate the array
For ($i=0; $i -le $arr.Length - 1; $i++) {
    $percent = $i / $arr.Length * 100
    Write-Progress -Activity "ActivityString" -Status "StatusString" -PercentComplete $percent -CurrentOperation "CurrentOperationString"

    $trigger = "f"

    For ($j = $i + 1; $j -le $arr.Length - 1; $j++)
    {
        foreach ($num in $arrDupNum)
        {
            #if statement to skip over duplicates already found
            if($num -eq $j -and $j -le $arr.Length - 2)
            {
                $j = $j + 1
            }            
        }

        if ($arr[$j].Name -eq $arr[$i].Name)
            {
                $trigger = "t"
                Add-Content H:\Desktop\blank.txt ($arr[$j].FullName + "; " + $arr[$i].FullName)
                Write-Host $arr[$i].Name
                $arrDupNum += $j
            }
    }
    #trigger used for formatting the text file in csv format
    if ($trigger -eq "t")
    {
    Add-Content H:\Desktop\blank.txt (" " + "; " + " ")
    }
}
马蒂亚斯·R·杰森

使用哈希表按名称对文件进行分组:

$filesByName = @{}

foreach($file in $arr){
    $filesByName[$file.Name] += @($file)
}

现在我们只需要找到包含多个文件的所有哈希表条目:

foreach($fileName in $filesByName.Keys){
    if($filesByName[$fileName].Count -gt 1){
        # Duplicates found!
        $filesByName[$fileName] |Select -Expand FullName |Add-Content .\duplicates.txt
    }
}

这样,当你有N文件时,你最多会迭代它们N*2几次,而不是N*N多次:)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

PowerShell - 重命名对象数组中的重复文件名

用于在文件中查找文件名并将其移动到不同目录的 Powershell 脚本

在PowerShell中查找具有不同文件名的最后修改文件

如何使PowerShell处理文件名中的[或]?

从powershell中的部分读取文件名

在 PowerShell 中重命名文件名

在Powershell中批量重命名照片并添加字母以重复文件名

如何使用Powershell检查重复的文件名?

在PowerShell中查找当前的当前季度以添加格式为“ yyyyqq”的文件名

Windows PowerShell在文件中查找重复的行

Powershell:在定义函数的位置查找文件名

文件名提取-Powershell

在Powershell文件名中按日期列出文件

如何使用PowerShell中的文件内容获取文件名

PowerShell:根据文件名中的日期删除文件

使用Powershell从目录中的列表中搜索文件名

从powershell中的文件名中删除特殊字符

如何在Powershell中拆分文件名并从中选择文件名?

使用 powershell 在文件名中附加字符串

PowerShell多条语句条件-比较文件名中的日期

Powershell从文件名中删除前导零

使用Powershell删除文件名中的方括号字符

使用PowerShell重命名或删除文件名中的字符

Powershell从文件名中删除特殊字符

使用PowerShell在文件名中搜索字符串

如何在PowerShell中解析文件名

使用powershell从文件名中获取时间戳

通过powershell从文件名中删除SXXXXX?

使用 Powershell 从文件名中删除前导零