PowerShell for Windows Admins

Sep 26 2013   12:58PM GMT

Rolling back time

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

There are many situations where you want to roll the date back – checking a file’s last access time, processing event logs, checking a password expiry in AD.

Get-Date (or more accurately the underlying System.DateTime .NET class offers a number of options.

Lets say you need a date that’s 3 months in the past.

You could create it directly:

£> Get-Date -Day 26 -Month 6 -Year 2013

26 June 2013 19:41:42

Alternatively:

£> Get-Date -Date “26 June 2013″

26 June 2013 00:00:00

Notice the difference on the times. I’m going to ignore the time portion.

Get-Date supplies a number of methods you could use:

Get-Date | Get-Member -MemberType Method

Add
AddDays
AddHours
AddMilliseconds
AddMinutes
AddMonths
AddSeconds
AddTicks
AddYears

£> $ts = New-TimeSpan -Days 91
£> $ts

Days : 91
Hours : 0
Minutes : 0
Seconds : 0
Milliseconds : 0
Ticks : 78624000000000
TotalDays : 91
TotalHours : 2184
TotalMinutes : 131040
TotalSeconds : 7862400
TotalMilliseconds : 7862400000

£> (Get-Date).Add(-$ts)

27 June 2013 19:46:06

£> (Get-Date).AddDays(-$ts.Totaldays)

27 June 2013 19:46:32

£> (Get-Date).AddHours(-$ts.TotalHours)

27 June 2013 19:48:32

£> (Get-Date).AddMinutes(-$ts.TotalMinutes)

27 June 2013 19:49:07

£> (Get-Date).AddSeconds(-$ts.TotalSeconds)

27 June 2013 19:50:18

£> (Get-Date).AddMilliseconds(-$total.TotalMilliseconds)

26 September 2013 19:51:19

£> (Get-Date).AddTicks(-$total.TotalTicks)

26 September 2013 19:51:38

You can also do

£> (Get-Date).AddMonths(-3)

26 June 2013 19:52:12

£> (Get-Date).AddYears(-0.25)

26 September 2013 19:52:37

Lots of ways to solve the same problem. While you normally wouldn’t want to calculate a date 3 months in the past based on seconds or ticks the fact that you can use those values opens up other possibilities.

The [datetime] class supplies a good set of methods for manipulating dates. Knowing they are there enables you to use the most appropriate to solve your task.

 Comment on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to: