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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With