Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
741 views
in Technique[技术] by (71.8m points)

powershell - How do I delete all .webp files in a directory based on if the duplicate .jpeg file (with the same .BaseName) has changed in the last 24 hours?

So, I have a directory of pictures for a website. There are pictures that are the same with both a .jpeg extension and a .webp extension. I want to write a PowerShell script that finds all the existing .jpeg files that changed in the last 24 hours, and then find the respective .webp file and delete the .webp file.

I've tried this to get all the .webp files that can be deleted but it doesn't seem to work:

$images = Get-ChildItem -Path $dir*.jpg, $dir*.webp | 
Group-Object { $_.BaseName } |
    Where-Object {($_.CreationTime -gt (Get-Date).AddDays(-1)) -or ($_.Group.Extension -notcontains '.jpg')} | 
        ForEach-Object Group

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think this is easier:

Get a list of basenames for the jpg files that were last modified as of yesterday, next get a list of files in the same directory with the .webp extension that have a BaseName matching one of the jpg basenames and then remove these.

$dir     = 'D:Test'
$refdate = (Get-Date).AddDays(-1).Date
$jpegs   = (Get-ChildItem -Path $dir -Filter '*.jpg' -File | Where-Object { $_.LastWriteTime -gt $refdate }).BaseName
Get-ChildItem -Path $dir -Filter '*.webp' -File | Where-Object { $jpegs -contains $_.BaseName } | Remove-Item -WhatIf

Onece you are satisfied the correct files are getting deleted, remove the safety -WhatIf switch and run again.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...