PowerShell Get-Date formatting

I sometimes use PowerShell to create files or logs that include the date or time. My preference is to write dates and times from greatest to smallest value. I also prefer to use the hyphen as a delimiter because it is filename friendly.

Here are the three most frequently used Get-Date -Format specifiers that I use and their formatted result:

1
2
3
4
5
6
PS D:\> Get-Date -Format yyyy-MM-dd
2016-06-08
PS D:\> Get-Date -Format HH-mm-ss
09-23-07
PS D:\> Get-Date -Format s | foreach {$_ -replace ":", "-"}
2016-06-08T09-23-07

When writing scripts, I often create these three variables that I may use throughout the rest of my script.

1
2
3
4
5
6
7
8
9
10
# Dates: Get Date and Time
$Date = Get-Date -Format yyyy-MM-dd
$Year = Get-Date -Format yyyy
$Month = Get-Date -Format MM
$Day = Get-Date -Format dd
$Hour = Get-Date -Format HH
$Minute = Get-Date -Format mm
$Second = Get-Date -Format ss
$Time = Get-Date -Format HH-mm-ss
$TimeStamp = Get-Date -Format s | foreach {$_ -replace ":", "-"}