Putting the date in a file name

I often need to create file names that include the date & time the file was created in the name. I’ve come up with all sorts of ways to do but this I think is the simplest.

I want the date in this format:  year-month-day-hour-minute-second.  In other words a format that is easily sortable. I discovered that if you convert a data to a string there is a formatter that does most of the work for you.  That’s a lower case s.

PS> (Get-Date).ToString("s")

You can’t have a : symbol in a file name so need to get rid of those

PS> (Get-Date).ToString("s").Replace(":","-")

To complete the file name

PS> $datestring = (Get-Date).ToString("s").Replace(":","-")
PS> $file = "c:\folder\Prefix_$datestring.txt"
PS> $file

I’ve done this as a two step process otherwise when you replace the : you also take out the one for the disk drive – oops


Published Wed, Apr 3 2013 20:18 by RichardSiddaway
Filed under:


# re: Putting the date in a file name

If you want to get this work with one line you can use it that way...

$file = "c:\folder\Prefix_$((Get-Date).ToString("s").Replace(":","-")).txt"

Wednesday, April 03, 2013 4:59 PM by BernhardW

# re: Putting the date in a file name

Another (easier) way is to use -Format parameter in the Get-Date cmdlet:

Cet-Date -Format dd-MM-yyyyThh-mm-ss

Thursday, April 04, 2013 6:48 AM by Vadims Podans

# re: Putting the date in a file name

To solve that "2step" problem following use could be used.


Saturday, April 06, 2013 4:18 AM by Vincent

Leave a Comment

If you can't read this number refresh your screen
Enter the numbers above: