Yong Cai
Yong Cai

Reputation: 147

Powershell get-childitem excludes a range of dates

I'm using Get-ChildItem to get all of the tomcat log files where the date is not equal to the current date/today. I would like to get the tomcat log files where the date is not in a range of dates. For example the filenames of the last 7 days shall not be listed.

Sample of tomcat logs filename:
catalina.2018-12-21.log
host-manager.2018-12-21.log

$date=Get-Date (get-date).addDays(-0) -UFormat "%Y-%m-%d"
$file=Get-ChildItem "C:\tomcat\logs" -exclude "*$date*"

foreach($files in $file)
{
    Move-Item -Path $files -Destination "C:\expiredlogs"
}

[.....]Get all of the logs filename where date is not in the last 7 days range from "C:\expiredlogs"

Is there any good, efficient way to retrieve all the filenames not in the range 7 days ago till now?

Upvotes: 0

Views: 949

Answers (3)

Janne Tuukkanen
Janne Tuukkanen

Reputation: 1660

Above mentioned method to use LastWriteTime is correct way to do this. But if there's time stamps in the filenames as you have, filtering could be more efficient than Where-Object and you can give it arrays.

First create an array of dates which should be excluded:

$range =  -3 .. -5 | ForEach-Object { "*$(Get-Date (Get-Date).addDays($_) -UFormat '%Y-%m-%d')*" }

Which today returns:

*2018-12-18*
*2018-12-17*
*2018-12-16*

And pass that to the Get-ChildItem:

Get-ChildItem "C:\tomcat\logs" -Exclude $range

Upvotes: 0

Palle Due
Palle Due

Reputation: 6292

If you insist on using the file names you need to parse the names to dates, since Get-ChildItem doesn't know about dates. Something like this should do the trick:

Get-ChildItem "c:\programdata\dgs\cathi\log" | `
where { ([DateTime]::ParseExact($_.Name.Substring($_.Name.Length-14,10),'yyyy-MM-dd', $null) -lt (Get-Date).addDays(-7))} 

The number 14 is not a magical number, it's the length of the date + '.log'.

Upvotes: 0

Mötz
Mötz

Reputation: 1722

I'm assuming that you just want to get all files, regardless of their name. Until now you based that on the file name itself, but you could base the search on the attributes of the files. In this example I'm getting all files that is 7 days old or newer.

$files=Get-ChildItem "C:\tomcat\logs" | Where-Object LastWriteTime -gt (Get-Date).AddDays(-7).Date

foreach($file in $files)
{
    Move-Item -Path $file -Destination "C:\expiredlogs"
}

The above code will only look at the write time for the file, regardless of the file name. You would limit that further if needed, by applying other filters.

Updated based on the recommendations from @LotPings

Upvotes: 1

Related Questions