DateTime-formatting with the PowerShell Format Operator -f on PowerShell 7

Dates and time records are nearly everywhere. Files, database entries, logs, you cannot avoid them when dealing with automation. So formatting them the the right way with a fast and powerful tool is key to light and effective code.

PowerShell offers the „Format Operator“ -f ever since and i thought its time to create a list of possibilities, and test them on PowerShell 7 for my own and of course for your reference. The below code was tested on PowerShell 7-preview6 and VS-Code on Windows 10 and MacOS with UI Culture de-DE.

The code is based on the .NET standard base types documentation. Link

First, lets generate a DateTime object of January 1st 2001 to have also days and months with one digits as examples:

General formatting syntax

If you never dealt with the format operator or are new to PowerShell, see an example below how it works. Left is a string „The DateTime is“ with an Index {0} to the date on the right hand side, right is the data we want to format, in our case the current DateTime.

Standard Format Strings

.NET offers a wide range of standard format strings which should cover 99% of your needs when dealing with dates and times.

Custom Format Strings

If you have a more complex demand on date/time formatting, the custom format strings should fulfill your needs. Below find a range of options with examples on custom formatting.

Using seperators in Custom Format Strings

If you want to combine date and/or time values in your custom formatting, you need to know there is a time seperator ‚:‘ and a date seperator ‚/‘. Now this lets us combine our custom date/time field to our own string.

Using escape characters in DateTime Strings

We know that there is always more then one path in PowerShell to solve a problem, but you should know, that it is possible to use escape characters in DateTime formatting. This allows us to create some YODA-Style time announcement 🙂

Hope that helped and is usable to you !

Regards/Roman