Garrett
Garrett

Reputation: 649

Powershell date range

I'd like to create a variable that contains a list of dates in the yyyy_MM_dd format, one week from a given date.

My current code works, but is not efficient or very clean. Ideally the oldest date (-6 days in the below example) would be a separate variable such as $lastDate = '-6' so that I can quickly make adjustments, while still having the script pull the following six days (one week) from the date indicated in $lastDate.

I plan to use this variable to find paths containing the date in the particular format, so it is ok if the output is a string and not a real 'date'. I do not want to use date filters on Get-ChildItem because the actual dates of the file paths are not accurate to the path names.

Current Script:

$range = (Get-Date).AddDays(-6).ToString('yyyy_MM_dd'), (Get-Date).AddDays(-5).ToString('yyyy_MM_dd'), (Get-Date).AddDays(-4).ToString('yyyy_MM_dd'), (Get-Date).AddDays(-3).ToString('yyyy_MM_dd'), (Get-Date).AddDays(-2).ToString('yyyy_MM_dd'), (Get-Date).AddDays(-1).ToString('yyyy_MM_dd'), (Get-Date).ToString('yyyy_MM_dd')

This returns the desired results:

2019_11_28
2019_11_29
2019_11_30
2019_12_01
2019_12_02
2019_12_03
2019_12_04

Can anyone suggest a cleaner or more efficient way to do this?

Upvotes: 0

Views: 1782

Answers (1)

JosefZ
JosefZ

Reputation: 30113

Maybe something like the following?

$range = -6..0 | 
    ForEach-Object { (Get-Date).AddDays($_).ToString('yyyy_MM_dd') }
$range
2019_11_28
2019_11_29
2019_11_30
2019_12_01
2019_12_02
2019_12_03
2019_12_04

Upvotes: 6

Related Questions