Formatting date and time to your needs is easy with the -Format parameter provided by Get-Date. You can use it either with the current date, or external DateTime variables. Simply use the wildcards for the date and time elements you want to convert to an output string.
Here are a couple of examples. To output the current date in ISO format, for example, run this:
PS> Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
To use a datetime object that already exists and that you might have read from somewhere else, submit it to Get-Date via -Date:
# find out last boot time
$os = Get-CimInstance -ClassName Win32_OperatingSystem
$lastBoot = $os.LastBootUpTime
# raw datetime output
# formatted string output
Get-Date -Date $lastBoot -Format '"Last reboot at" MMM dd, yyyy "at" HH:mm:ss "and" fffff "Milliseconds.
The format string accepts both the wildcards for datetime components, and static text. Just make sure you enclose static text in double quotes. Here is the result (on my German system):
Donnerstag, 22. November 2018 01:13:44
Last reboot at Nov 22, 2018 at 01:13:44 and 50000 Milliseconds.
psconf.eu – PowerShell Conference EU 2019 – June 4-7, Hannover Germany – visit www.psconf.eu There aren’t too many trainings around for experienced PowerShell scripters where you really still learn something new. But there’s one place you don’t want to miss: PowerShell Conference EU - with 40 renown international speakers including PowerShell team members and MVPs, plus 350 professional and creative PowerShell scripters. Registration is open at www.psconf.eu, and the full 3-track 4-days agenda becomes available soon. Once a year it’s just a smart move to come together, update know-how, learn about security and mitigations, and bring home fresh ideas and authoritative guidance. We’d sure love to see and hear from you!
ReTweet this Tip!
The final command is missing "' (double quote, single quote) to first close out "Milliseconds. and secondarily to close out -Format argument.
Powered by IDERA