简体   繁体   English

Powershell 脚本搜索相似文件名

[英]Powershell script to search for similar filenames

I am trying to build a PowerShell script that can search for files with similar names inside of a folder.我正在尝试构建一个 PowerShell 脚本,该脚本可以在文件夹中搜索具有相似名称的文件。

The files will always have a similar name template:这些文件将始终具有相似的名称模板:

filename(C).TIF
filename(M).TIF
filename(Y).TIF
filename(K).TIF

All I need to do is to extract the "filename", check if there are 4 similar ones (C,M,Y,K) and use it as a variable to move those files.我需要做的就是提取“文件名”,检查是否有 4 个相似的(C、M、Y、K)并将其用作移动这些文件的变量。

$files = Get-ChildItem -Path "E:\test" -Filter "*.TIF" |
    Foreach-Object {$_.BaseName} | Sort-Object -Unique 

$files = $files -replace ".{3}$" 

$names = (Get-Unique -InputObject $files)  
$names

The result looks like this:结果如下所示:

jobname 
jobname 
jobname 
jobname 
test 
test 
test 
test

But I need to sort by unique and count them, maybe, before action.但我需要按唯一性排序并计算它们,也许是在行动之前。

But I need to sort by unique and count them, maybe, before action.但我需要按唯一性排序并计算它们,也许是在行动之前。

You definitely want the Group-Object cmdlet !您肯定需要Group-Object cmdlet

As the name suggests, it... groups objects , based on some common property:顾名思义,它...分组 objects ,基于一些共同的属性:

$filesByCommonBaseName = Get-ChildItem -Path "E:\test" -Filter "*.TIF" |Group-Object { $_.BaseName -replace '.{3}$' }

Now that you have them grouped correctly, you can start operating on them as such:现在您已将它们正确分组,您可以开始对它们进行操作:

foreach($entry in $filesByCommonBaseName){
    Write-Host "Operating on files starting with $($entry.Name)"
    if($entry.Count -eq 4){
        # we found four matches, delete them!
        $entry.Group |Remove-Item -Force
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM