Reputation: 2127
I have a list of files in a directory with different dates as such:
1. test_2017-01-01.csv
2. test_2017-02-01.csv
3. test_2017-03-01.csv
4. test_2017-04-01.csv
Let's say I want to pull all the files into a new list labeled $files
that holds only files between the dates of 2017-01-01 and 2017-03-01. How would I go about this? I Can pull from the directory at the moment as such:
$files = Get-ChildItem "my_directory" | Sort-Object
Upvotes: 1
Views: 634
Reputation: 158
not sure this can be easily transformed to date format query. Do you think regex would work for you in this case?
$files = Get-ChildItem | Where-Object {$_.Name -match "^test_2017-0[123]{1}-01.csv$"}
There is quite some long one-liner, but it does what you are after - converts the numeric string in the name of file (has to have format of yyyy-MM-dd) to date and then evaluates whether it's in range specified.
$files = Get-ChildItem | Where-Object {($_.Name -match "[\d]{4}-[\d]{2}-[\d]{2}") -and ([datetime][regex]::Match($_.Name, "[\d]{4}-[\d]{2}-[\d]{2}").Value -ge (Get-Date 2017/01/01)) -and ([datetime][regex]::Match($_.Name, "[\d]{4}-[\d]{2}-[\d]{2}").Value -le (Get-Date 2017/03/01))}
Upvotes: 2