2

There are multiple .webp files in a project folder. Some .webps are the original picture and some function as thumbnail (their size is different). The used naming convention is: original files are just called NAME.webp and tumbnails are NAME-thumb.webp. I am trying to create a Powershell script that returns all the -thumb.webp files based on the original files creation date. So, if the original files was created today, return the corresponding -thumb.webp (they have the same basename apart from the -thumb

This is what I tried so far, but something is still off:

$webps = (Get-ChildItem -Path $dir -Filter '*.webp' -File | Where-Object { $_.CreationTime -gt $refdate }).BaseName
$output = Get-ChildItem -Path $dir -Filter '*.webp' -File | Where-Object { $webps -contains ($_.BaseName + "-thumb") }
Hajo Brandt
  • 113
  • 7

2 Answers2

3
Get-ChildItem $dir\*.webp -Exclude *-thumb.webp -File | 
    Where-Object CreationTime -gt $refdate | 
    ForEach-Object { $_.Fullname -replace '\.webp$', '-thumb.webp' }

First we get all *.webp files, excluding *-thumb.webp files. Using Where-Object we select only files whose CreationTime is greater than $refdate. Finally we replace .webp by -thumb.webp to return the full paths of the thumbnail files.

If you only need the filenames, replace $_.Fullname by $_.Name.

mklement0
  • 382,024
  • 64
  • 607
  • 775
zett42
  • 25,437
  • 3
  • 35
  • 72
2

Group-Object can help:

$refDate = (Get-Date).Date # today's calendar day, for instance.

Get-ChildItem -File -Path $dir -Filter *.webp |
  Group-Object { $_.BaseName -replace '-thumb$' } | # by base name without suffix
    ForEach-Object {
      # Test the creation date of the non-thumbnail *.webp file,
      # which comes alphabetically first in the group.
      if ($_.Group[0].CreationTime -gt $refDate) {
        $_.Group[1] # Output the corresponding *-thumb.webp file
      }
    }
  • -replace '-thumb$' uses the -replace operator to remove the -thumb suffix from the file base names, so that <name>.webp and <name>-thumb.webp files with the same <name> are grouped together.

  • The above assumes that every <name>.webp file has a <name>-thumb.webp counterpart, in which case each $_.Group array contains two System.IO.FileInfo instances, with the first always representing the <name>.webp, and the second the <name>-thumb.webp file, because Compare-Object sorts the group members by the grouping criterion/a.

mklement0
  • 382,024
  • 64
  • 607
  • 775