Creating an Array of Dates within a Date Range with PowerShell
Today I needed to create an array of all the dates in a data range in PowerShell. It’s a simple little thing. Maybe I should have asked Github Copilot, but I’m old skool, so I wrote it myself. (I also haven’t gotten used to having a virtual assistant!)
The reason I even needed to do this is the dread 5000 item view threshold in SharePoint lists and libraries. We have a list with about 1.6 million items in it, and I wanted to “slice out” the ones which matched a specific date range. No matter how I tried to do that in the UI, I failed – not surprisingly, since there are about 1500 items per date.
You might ask why we’d have so many items in a list. Well, this is a list that’s built up over 7 years, and we actually need all the data in it together. I built an app in Angular years ago which uses it as a data source, and that app works just fine. This request for a year’s worth of data is an anomaly, and not something I considered in my design.
I hit on the idea to use PnP.PowerShell to grab the items for each day in the date range and combine them all together. But first, I needed a valid list of all the dates in that year range. Thus, my little script here. I think it’s self-explanatory, but feel free to ask questions in the comments. One note: you could change the format in line 11 to meet your own needs.
# Set up list of days we want
$days = @() # Array to hold all the dates
# Start and end date for the range
$startDate = [DateTime] "2022-05-01"
$endDate = [DateTime] "2023-04-30"
# Loop through, adding one date to the array at a time until we reach the end date
$date = [DateTime] $startDate
while ($date -le $endDate) {
$days += $date.ToString('yyyyMMdd')
$date = $date.AddDays(1)
}
# And here's our final array!
$days
That’s pretty cool, I didn’t know about “[DateTime]” that you can set it to a value.
Using my PowerShellAI module at the cli. Took < 1min to ask and have it answered:
“`
chat 'using powershell, create and array of dates between "2022-05-01" and "2023-04-30", in year month day format'
“`
Returned
“`powershell
# Define start and end dates
$start = Get-Date "2022-05-01"
$end = Get-Date "2023-04-30"
# Create an empty array to store the dates
$dates = @()
# Loop through each day between the start and end dates
while ($start -le $end) {
# Add the date to the array in 'year-month-day' format
$dates += $start.ToString('yyyy-MM-dd')
# Increment the date by 1 day
$start = $start.AddDays(1)
}
# Output the array of dates
$dates
“`