The Surly Admin

Father, husband, IT Pro, cancer survivor

Quick Script: Date Ranges

Ever need to get an array of all the days between two dates?  This script will calculate the date range and load up an array with date/time objects for every date in between the entered times:

Function Get-DateRange
{ [CmdletBinding()]
Param (
[datetime]$Start = (Get-Date),
[datetime]$End = (Get-Date)
ForEach ($Num in (0..((New-TimeSpan Start $Start End $End).Days)))
{ $Start.AddDays($Num)

To use it, simply call the function

  • Get-DateRange
  • Get-DateRange -Start 7/24/14 -End 8/1/14
  • Get-DateRange -End 7/20/14

And just to pretty it up as a Function and with comment-based help:

Function Get-DateRange
{ <#
Find out all the dates inbetween the range of dates you specify
Simple function to return an array of date/time objects for all days inbetween the two dates
you specify.
Start date – this specifies the beginning of your range
End date – this specifies the ending of your range. This date can be before OR after the Start
Get-DateRange -Start 7/24/14 -End 7/1/14
Get all of the dates between the 24th to the 1st in reverse order. 24 DateTime objects will
be returned.
Get-DateRange -End 8/1/14
Get all of the dates between today and 8/1/14. As of 7/14/14 that would be 8 dates.
Author: Martin Pugh
Twitter: @thesurlyadm1n
Spiceworks: Martin9700
1.0 Initial Release
Param (
[datetime]$Start = (Get-Date),
[datetime]$End = (Get-Date)
ForEach ($Num in (0..((New-TimeSpan Start $Start End $End).Days)))
{ $Start.AddDays($Num).Date


July 25, 2014 - Posted by | PowerShell |

1 Comment »

  1. Like your script. I have a script that creates a a license usage. Script runs every hour and sends the output to a csv file. Customer no longer wants to see the entire usage but just the high water mark for each day. Created a script that will do that but it is a manual process. file is created with the date I.E. 2022-04-26.csv. I tried using your script to automate this process so on Monday it would walk through the previous 7 days and grab the high water mark from each file. When I try to use this. [datetime]$start = Get-Date -date $(Get-Date).AddDays(-8) -UFormat “%y/%m/%d” I get a this error.
    Cannot convert value “22/04/20” to type “System.DateTime”. Error: “String was not recognized as a valid DateTime.” Any help would be appreciated.

    Comment by Stan Mitterling | April 28, 2022 | Reply

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: