Search code examples
powershellget-childitem

How to return files in powershell with the same extension, but containing a specific end to the name?


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") }

Solution

  • 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.