Learn about Windows PowerShell
Summary: Easily customize the way Windows PowerShell displays a date.
How can I use Windows PowerShell to easily display the date as day-dash-month-dash-four-digit year?
Use the Get-Date cmdlet,specify a custom format by using the Format parameter, and use dd for the date, M for the month and yyyy for a four-digit year (this is case sensitive):
Get-Date -Format "dd-M-yyyy"
I find this more flexible:
PS C:\scripts> $dt=[datetime]'02/03/2001'
PS C:\scripts> $dt
Saturday, February 03, 2001 12:00:00 AM
PS C:\scripts> $dt.ToString('yyy-mm-dd')
PS C:\scripts> $dt.ToString('yyy-M-dd')
PS C:\scripts> $dt.ToString('yyy-M-d')
One thing to keep in mind is that if you call Get-Date -Format (or -UFormat), you're no longer getting back a DateTime object from the cmdlet. You're getting a string. That may be important, depending on how you're using the cmdlet's return value.
@JRV you are right, it does offer a lot of flexibility. Keep in mind, these are overloads to ToString. I can therefore also do this: (get-date).tostring('yyy-mm-dd')
@Dave Wyatt This is a great point, once I call one of these methods I no longer have a System.DateTime object, but a System.String object. Still, for certain types of activities it is a great technique.
I think you mean that they are overloads to System.Object which supports a generic string method that returns the class name if no overload is defined. The overload is defined in [datetime] and is a formatter. It is the same one used internally by Get-Date.
Yes -Get-Date cand do that as well but when you paren the Get-Date (Get-Date you are referencing the retuned object which is ... System.DateTime. It is a method on the returned object and not on Get-Date. CmdLets really have no methods. They only have return types.
So yours is much the same but still different. All methods work and are useful. I just like how explicit the following are:
and many, many more.
@JRV indeed. [datetime]0 a cute way to get 1/1/1. [datetime]::now returns same as Get-Date -- (for me Get-Date is easier to type)
Keep in mind that PowerShell cmdlets freqently add additional properties to the objects they return. These properties are not present if you create the underlying .NET object yourself.
For Get-Date, the only such property that I can see is "DisplayHint", which you would probably never miss, but this might be more of a problem with other cmdlets and classes.
Compare-Object ([DateTime]::Now | Get-Member) (Get-Date | Get-Member) | Format-Table -AutoSize
@Ed - yes - it is much a matter of what we are used to and preferences. It is good to know about all methods as both have their strengths and weaknesses.