【问题标题】:Using Powershell, how to return a list of files based on the existence of duplicate files with a different naming convention?使用Powershell,如何根据不同命名约定的重复文件的存在返回文件列表?
【发布时间】:2021-01-13 22:18:11
【问题描述】:

一个项目文件夹中有多个 .webp 文件。有些.webps 是原始图片,有些用作缩略图(它们的大小不同)。使用的命名约定是:原始文件仅称为 NAME.webp,缩略图为 NAME-thumb.webp。

我正在尝试根据相应的 thumb-webp 是否存在来返回所有 .webp 文件。因此,如果图片 SAMPLE.webp 有 SAMPLE-thumb.webp,请不要将此文件添加到列表中。但是如果 SAMPLE.webp 没有对应的 SAMPLE-thumb.webp,那么就在列表中做吧。

这是我迄今为止尝试过的:

$example = Get-ChildItem -File $dir\*.webp |
        Group-Object { $_.BaseName } |
          Where-Object { $_.Name -NotContains "-thumb" } |
            ForEach-Object Group

【问题讨论】:

    标签: powershell get-childitem


    【解决方案1】:

    您可以在不使用 Where-Object 和测试路径的情况下进行分组。

    Get-ChildItem -File $dir\*.webp |
        Where-Object {$_.Name -notmatch "-thumb" -and -not(Test-Path ($_.FullName -replace ".webp","-thumb.webp"))}
    

    这应该会为您提供没有相应缩略图文件的所有文件的列表。

    【讨论】:

      【解决方案2】:

      您可以执行以下操作:

      (Get-ChildItem $dir\*.webp -File |
          Group-Object {$_.BaseName -replace '-thumb$'} |
              Where Count -eq 1).Group
      

      你必须对分组有共同点。替换 BaseName 属性中的结尾 -thumb 会创建它。如果没有filenamefilename-thumb,则生成的GroupInfo 的计数值为1

      使用语法().Group 返回所有文件对象。如果您想针对每个文件处理代码,您可以改用Foreach-Object

      Get-ChildItem $dir\*.webp -File |
          Group-Object {$_.BaseName -replace '-thumb$'} |
              Where Count -eq 1 | Foreach-Object {
                  $_.Group
              }
      

      【讨论】:

        猜你喜欢
        • 2013-10-25
        • 2022-01-11
        • 2019-06-11
        • 1970-01-01
        • 1970-01-01
        • 2019-09-25
        • 1970-01-01
        • 1970-01-01
        • 2022-01-14
        相关资源
        最近更新 更多