If you are like me you use date time values constantly in PowerShell. From simply displaying the current date and time in progress message to using different values to create file or folder names. The Get-Date cmdlet has a -Format parameter which you can use. The tricky part is remembering what values to specify. Especially because they are case-sensitive. The values are documented at http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo%28VS.85%29.aspx.
ManageEngine ADManager Plus - Download Free Trial
Exclusive offer on ADManager Plus for US and UK regions. Claim now!
So to make my life (and maybe yours) easier, I wrote a little PowerShell script to remind me of the possible values.
$patterns = "d","D","g","G","f","F","m","o","r","s", "t","T","u","U","Y","dd","MM","yyyy","yy","hh","mm","ss","yyyyMMdd","yyyyMMddhhmm","yyyyMMddhhmmss" Write-host "It is now $(Get-Date)" -ForegroundColor Green foreach ($pattern in $patterns) { #display text "{0}`t{1}" -f $pattern,(Get-Date -Format $pattern) } #foreach Write-Host "Most patterns are case sensitive" -ForegroundColor Green
The variable $patterns is an array of commonly used datetime format values. Many of them were pulled from that MSDN page but I added some of my own at the end. Here's the output from this script.
This looks nice, and is definitely a nice cheat sheet. But then I realized since I'm writing a script I should take this to the next level and write a useful object to the pipeline.
$patterns = "d","D","g","G","f","F","m","o","r","s", "t","T","u","U","Y","dd","MM","yyyy","yy","hh","mm","ss","yyyyMMdd","yyyyMMddhhmm","yyyyMMddhhmmss" Write-host "It is now $(Get-Date)" -ForegroundColor Green foreach ($pattern in $patterns) { #create an Object [pscustomobject]@{ Pattern = $pattern Syntax = "Get-Date -format '$pattern'" Value = (Get-Date -Format $pattern) } } #foreach Write-Host "Most patterns are case sensitive" -ForegroundColor Green
This version creates a custom object for each pattern, including the syntax.
An alternative to -Format is to use the ToStringMethod() specifying the format pattern.
PS C:\> (get-date).ToString('o') 2014-10-08T07:58:46.0376740-04:00
Because this is an object I can pipe it to other cmdlets.
C:\scripts\Test-DatePattern.ps1 | format-table
I included the syntax so all you need to do is copy and paste. Or, how about this?
Function Insert-Pattern { C:\scripts\Test-DatePattern.ps1 | Out-GridView -Title "Select a format" -OutputMode Single | foreach { $psise.CurrentFile.Editor.InsertText($_.Syntax) } }
Define this function in the PowerShell ISE, perhaps even adding it to your Add-Ons menu with a keyboard shortcut. When executed, you'll get a graphical display using Out-Gridview.
Select a pattern and the syntax gets pasted into your PowerShell script. I love making PowerShell do my work for me! Enjoy.