Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get child items with date filetypes using regex in Powershell

I am dealing with many files that have a file extension such as .20180615 (yyyyMMDD). I am looking for a way to access all files with a date filetype using regex. The only solution I have right now is to use *2 to get all files with a filetype starting with 2, but I would prefer a solution that used regex to generalize across all dates in the yyyyMMDD format.

Get-ChildItem -Path $path -Recurse *2
like image 463
Nate Avatar asked Oct 24 '25 22:10

Nate


1 Answers

There are many solutions to this issue. Most choices could just be based on personal preference but there could be performance and validation limitations concerns.

When dealing with files it is always more suitable to try and use the built-in filtering as opposed to post-processing with Where-Object and the like. It affects performance especially when -recurse is involved. The limitation is basic wildcard support for Get-ChildItem -Path. So, with that in mind, LotPings comment covers that solution.

Get-ChildItem -Path "$path\*.20[01][0-9][01][0-9][0-3][0-9]" -Recurse

You should be covered until the year 2099!


You tagged regex so a simple Where-Object filter for that would just be

Get-ChildItem -Path $path -Recurse | Where-Object{$_.Extension -match '^\d{8}$'}

Lacks some validation but if the extension is 8 digits you are good to go.


Another approach that validates your criteria better would be to only allow files with valid dates

Get-ChildItem -Path $path -Recurse | Where-Object{
    try{
        [datetime]::ParseExact($_.Extension,"yyyyMMdd",[System.Globalization.CultureInfo]::InvariantCulture)
    } catch {
        $false
    }
} | ForEach-Object{
    # Do stuff
}

If there is a valid date in the extension that file (or folder) will get passed down the pipeline. That being said if you have at least psv3 consider the -File switch for Get-ChildItem.

like image 137
Matt Avatar answered Oct 27 '25 13:10

Matt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!