PowerShell’s Get-Date FileDateTime for Safe Filenames

Since about the beginning of time now, I’ve used Get-Date to create my own safe filenames. It’s a date and time format that is safe to be used as/in a file’s name without including anything that can’t be. Here’s what I’ve long used.

That’ll produce something such as this.

Okay, maybe I haven’t always used this, but I certainly used a variation. It was after the beginning of time, if you will, that I switched to this version, which includes the dot and the seven Fs. The Fs (in lowercase [it’s important]) display milliseconds. I added these to help ensure that filenames that include the date and time were more likely to be unique. You can imagine. You create more than one file in the same second, and you run up against a file already existing error if you don’t include milliseconds. Before we continue, let’s ensure all the other letters represented in the above code example are included here:

D Stand-In letter for Date T Stand-In letter for Time
y Year (4 for 4-digit year) H Hour (2 for 2-digit hour)
M Month (2 for 2-digit month) m Minute (2 for 2-digit minute)
d Day (2 for 2-digit day) s Second (2 for 2-digit second)

I should mention, that using this format ensures proper file sorting and ordering. That can be important. It’s always been there (or it’s likely, at least), but it turns out that there’s an easier way than what I’ve been doing. Join me at https://tommymaynard.com to learn (or be reminded) about it (direct link).

≥ Tommy Maynard (Twitter: @thetommymaynard)

About Tommy Maynard

IT Pro. Passionate for #PowerShell, #AWS (certified x2), & all things automation. I'm not done learning. Author in #PSConfBook. Writes at https://powershell.org.