Reputation: 11
I'm new here and need some advice. Every month I upload movie trailers to a folder with the screening date in the file name. For example 230315_asterix...mp4, 230320_creed3.mp4. I would need the script to compare today's date with the date in the title every day. If the data matches, delete the file. At the end of the month, the folder will remain empty. Our cinema does not show every day. I've been trying to figure out the right shape of powershell lines for several nights now. Can you help me pls, or at least give me a push.
$refDate = ((Get-Date).AddDays(0) | Get-Date -Format 'yyMMdd‘)-Replace('/','\')
Get-ChildItem -Path 'C:\test' -Filter '*.mp4' -File |
Where-Object { $_.BaseName -match '(\d{1})-\d{6}$'} |
ForEach-Object {
$file = $_.FullName
try {
$date = [datetime]::ParseExact($Matches[1], 'yyMMdd', $null)
if ($date -lt $refdate) {
$_ | Remove-Item -WhatIf
}
}
catch {
Write-Warning "File $file is done."
}
}
Upvotes: 1
Views: 211
Reputation: 174485
I think you might be overthinking this - simply use the date string as part of the filter when discovering the files:
$datePrefix = Get-Date -Format 'yyMMdd'
Get-ChildItem -Path 'C:\test' -Filter "${datePrefix}*.mp4" -File |Remove-Item
Upvotes: 2