Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I have many files with different names per day. How can I filter them by the date in their name?

For example:

app_20130505.log
app_20130506.log
app_20130507.log
app_20130508.log
app_20130509.log

And my code snippet:

$RetainedDays = 7
$FileNameRegex = "\w+_(\d+)\.\w+"
$ArchiveBoundary = $(Get-Date -Format yyyyMMdd) - $RetainedDays
$ProcessFiles = Get-ChildItem -Path $RootPath -Recurse |
    Where-Object { $_.Name -match $FileNameRegex }

I have regex filter for it : \w+_(\d+)\.\w+, that gives me back the date in $Matches variable, but how can I combine them, and get back the file list, with those files, which older than 7 days?

share|improve this question
    
I think questions like this are better for stackoverflow then serverfault. –  tony roth May 9 '13 at 15:28
    
It's possible, but I doesn't know, how can I move the question into stackoverflow. Otherwise it's not a programming question. PowerShell is a script language, what is useful to system administrators, like me and possibly for you. –  gazsiazasz May 9 '13 at 19:52
add comment

2 Answers 2

See if this helps get you closer to what you're trying to do.

$RootPath = "C:\temp"
$ProcessFiles = @()
$RetainedDays = 7
$Today = get-date -format yyyyMMdd
$FileNameRegex  = "\w+_(\d+)\.\w+"
foreach ($File in Get-ChildItem -Path $RootPath) {
   $match = [regex]::matches($File, $FileNameRegex )
   $FileNameDate = $match[0].Groups[1].Value
   if (($Today - $FileNameDate) -ge $RetainedDays) { $ProcessFiles += $File }
}
$ProcessFiles
share|improve this answer
    
And I agree with Tony, stackoverflow would be the better choice. –  Bruce May 9 '13 at 20:29
add comment

It's not too nice, but works! :)

$RetainedDays = 14

$ArchiveBoundary = (Get-Date).AddDays(-$RetainedDays).ToString('yyyyMMdd')

$ProcessFiles = Get-ChildItem -Path $RootPath -Recurse |
    Where-Object { ($_.BaseName -split '_|\.')[1] -lt $ArchiveBoundary }
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.