header image

Putting the date in a file name

Posted by: | April 3, 2013 | 3 Comments |

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


under: PowerShell V3


  1. By: BernhardW on April 3, 2013 at 4:59 pm      

    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”

  2. By: Vadims Podans on April 4, 2013 at 6:48 am      

    Another (easier) way is to use -Format parameter in the Get-Date cmdlet:
    Cet-Date -Format dd-MM-yyyyThh-mm-ss

  3. By: Vincent on April 6, 2013 at 4:18 am      

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