Monthly Archive

Categories

Its a date

If you’ve used PowerShell for any length of time you have come across the Get-Date cmdlet

 

PS> Get-Date

13 September 2011 20:47:50

 

The cmdlet returns a .NET System.DateTime object.  The object has some methods we can use

PS> Get-Date | Get-Member -MemberType method

Add
AddDays
AddHours
AddMilliseconds
AddMinutes
AddMonths
AddSeconds
AddTicks
AddYears
CompareTo
Equals
GetDateTimeFormats
GetHashCode
GetType
GetTypeCode
IsDaylightSavingTime
Subtract
ToBinary
ToFileTime
ToFileTimeUtc
ToLocalTime
ToLongDateString
ToLongTimeString
ToOADate
ToShortDateString
ToShortTimeString
ToString
ToUniversalTime

 

Notice the list of methods for adding to the date

AddDays
AddHours
AddMilliseconds
AddMinutes
AddMonths
AddSeconds
AddTicks
AddYears

which we use like this

PS> (Get-Date).AddDays(2)

15 September 2011 20:50:52

PS> (Get-Date).AddHours(2)

13 September 2011 22:51:00

PS> (Get-Date).AddMilliseconds(250)

13 September 2011 20:51:20

PS> (Get-Date).AddMinutes(20)

13 September 2011 21:11:36

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

13 December 2011 20:51:51

PS> (Get-Date).AddSeconds(35)

13 September 2011 20:52:38

PS> (Get-Date).AddTicks(3500)

13 September 2011 20:52:16

PS> (Get-Date).AddYears(3500)

13 September 5511 20:52:30

 

Now these are all going forward.  We don’t have methods for subtracting from a date but we can do this

PS> Get-Date

13 September 2011 20:53:47

PS> (Get-Date).AddDays(-2)

11 September 2011 20:54:01

 

We use the Add*** methods with a negative value

 

The other alternatives to this involve using a TimeSpan

PS> $ts = New-TimeSpan -Days 10
PS> (Get-Date) + $ts

23 September 2011 20:55:33

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

23 September 2011 20:55:45

PS> (Get-Date) - $ts

03 September 2011 20:55:54

PS> (Get-Date).Subtract($ts)

03 September 2011 20:56:08

 

As with many things in PowerShell there are a number of ways to solve a problem

Leave a Reply