PowerShell Demo: Date, Time and Hours.
This TechNet Wiki is to demo the usage of Date, Time and Hours.
Summary
Everyone has their way of coding or they will align with the business requirement. In this article, we will demo the usage of Date, Time and Hours using PowerShell. How to Begin? Before we begin let's show how to search commands in PowerShell. This will save more time for scripters.
Search Command
Get-Command -Name '*date*' Get-Command -Name '*Time*' |
Date
Get-Date #OutPut: Thursday, June 19, 2014 2:11:14 PM (Date).DateTime #outPut:Thursday, June 19, 2014 2:11:14 PM |
Add Days
(Get-Date).AddDays(1) #OutPut: Friday, June 20, 2014 2:15:19 PM (Date).AddDays(1) #OutPut: Friday, June 20, 2014 2:15:19 PM [DateTime]::Now + 1d #OutPut: Friday, June 20, 2014 2:15:19 PM [DateTime]::Now.AddDays(1) #OutPut: Friday, June 20, 2014 2:15:19 PM |
Subtract Days
PowerShell is cool, you can easily do it using negative numbers
(Get-Date).AddDays(-1) #OutPut: Friday, June 20, 2014 2:15:19 PM (Date).AddDays(-1) #OutPut: Friday, June 20, 2014 2:15:19 PM |
Catch here is we can't use the cool stuff [DateTime]::Now - 1d is not supported. :). So when you code for logs management like removing old files? Please opt for the method which works as expected.
PowerShell Trick
[DateTime]::Now.Add(-1) |
PowerShell One Liner
[DateTime]::Now.AddDays(1).AddHours(2).AddMinutes(3).AddYears(1) #OutPut: Saturday, June 20, 2015 4:29:39 PM (Date).AddDays(1).AddHours(2).AddMinutes(3).AddYears(1) #OutPut: Saturday, June 20, 2015 4:29:39 PM [DateTime]::Now.AddDays(1).AddHours(2).AddMinutes(3).AddYears(1) #OutPut: Saturday, June 20, 2015 4:29:39 PM |
Conclusion
Suggest using [DateTime] which consumes less time for execution but not much difference between Get-Date. Enjoy PowerShell :)