#PSTip Working with DateTime objects in PowerShell using [System.DateTime]

When working with dates in PowerShell it is often useful to leverage the .NET Framework System.DateTime class. For example to display the current date and time the Now method can be used:

[System.DateTime]::Now

[System.DateTime] can be shortened to [DateTime] as shown in the following example, where it is used incombination with the Today method to display the current date:

[DateTime]::Today

When working with time stamps found in Active Directory the FromFileTime method can be used to convert the file time to a human readable format.

[DateTime]::FromFileTime(129955032000000000)

Another very useful feature is the ParseExact method that is included in this class. It transforms a string into a DateTime object. It can be used to convert almost any type of date by specifying the format using the MM-dd-yyyy notation. Running the following command will create a DateTime object that display the date correctly as the 16th of May, 2005.

[DateTime]::ParseExact('16@05==5','dd@MM==y',$null)

For more information about the DateTime methods available in this class, please refer to this MSDN article: http://msdn.microsoft.com/en-us/library/497a406b.aspx

About the author: Jaap Brasser

Jaap is a Senior System Engineer in the Financial Services industry. He focuses on Microsoft and related technologies and has a passion for PowerShell. In his spare time he maintains his Blog, Twitter feed, @Jaap_Brasser, and contributes on the Official Scripting Guys Forum and Windows PowerShell TechNet forums

Related Posts

%d bloggers like this: