I have a directory with multiple .log files with different dates. For example, abc_10_28_2020.log, 2_abc_10_28_2020.log, abc_10_27_2020.log, etc. I have been trying to write a compress PowerShell script to zip the same dated log files into 1 zip file on a daily basis. I have found some success using 7zip because my PowerShell version is not v5. However, my problem is that I do not know how to filter by yesterday's date when trying to zip up that day's logs.
My code works so far to compress all the abc files into a zip, but I cannot filter by date.
$yesterday = [DateTime]::Today.AddDays(-2).ToString("yyyy_MM_dd")
$path = "C:\Users\Sample\TEST\"
$newname = "test.zip"
if (-not (test-path "$env:ProgramFiles\7-Zip\7z.exe")) {
throw "$env:ProgramFiles\7-Zip\7z.exe needed"
}
set-alias sz "$env:ProgramFiles\7-Zip\7z.exe"
cd "C:\Users\Sample\TEST\"
sz a -tzip "$newname" $path.Fullname -i!*abc*.log
So in the above example, I was able to filter by abc, but not the date. I don't believe the 7zip command would allow $yesterday as that has not worked for me.
I suppose your log files all have the same date format? Also, why do you write AddDays(-2)
if you want yesterday? I suppose you mean AddDays(-1)
A very simple approach to get only yesterday's files would be a wildcard filter:
$filter = (Get-Date).AddDays(-1).ToString("MM_dd_yyyy")
$files = Get-ChildItem $path -Filter "*$filter.log"
Or, if you just want files older than 1 day you can do:
$today = (Get-Date).Date
Get-ChildItem $path | where {
($today - [DateTime]($_.Name -replace '.*(\d{2})_(\d{2})_(\d{4}).*', '$3-$1-$2')).TotalDays -ge 1
}