Sign up ×
Server Fault is a question and answer site for 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:


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

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 }
share|improve this answer
And I agree with Tony, stackoverflow would be the better choice. –  Bruce May 9 '13 at 20:29

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

Your Answer


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.