Working With TimeSpan Objects
TimeSpan objects represent a given amount of time. They are incredibly useful when you calculate with dates or times because they can represent the amount of time between two dates, or can add a day (or a minute) to a date to create relative dates.
Here are some samples to get you started:
# get a timespan representing one day and 3 hours:
New-TimeSpan -Days 1 -Hours 3
# get a timespan representing the time difference between now and next Christmas
New-Timespan -End '2013-12-24 18:30:00'
# get a timespan by subtracting two dates:
[DateTime]'2013-12-24 18:30:00' - (Get-Date)
# get a timespan by subtracting a timespan representing one day from a date:
(Get-Date) - [TimeSpan]'1.00:00:00'
# getting a specific property from a timespan (for example just the days):
$days = (New-Timespan -End '2013-12-24 18:30:00').Days
"Days to Christmas: $days"
# negating a timespan:
$timespan = New-TimeSpan -Days 1
$timespan.Negate()
$timespan
# creating a negative timespan directly:
New-TimeSpan -Days -1
ReTweet this Tip!