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”)
2013-04-03T20:09:31
You can’t have a : symbol in a file name so need to get rid of those
PS> (Get-Date).ToString(“s”).Replace(“:”,”-“)
2013-04-03T20-10-02
To complete the file name
PS> $datestring = (Get-Date).ToString(“s”).Replace(“:”,”-“)
PS> $file = “c:\folder\Prefix_$datestring.txt”
PS> $file
c:\folder\Prefix_2013-04-03T20-16-48.txt
PS>
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
Enjoy
Only because I just personally don’t like all the dashes, I usually use something like this:
$datestring = (Get-Date).ToString(“yyyyMMdd_HHmmss”)
Hi Richard!
This does not work well for international use cases!
(Get-Date).ToString(“s”) returns on an American Windows a Date with slashes! And slashes are not allowed in paths!
To have in every country of the world, the same result I prefer to use this approach:
(Get-Date).Tostring(“yyyy-MM-ddThh-mm-ss”)
Only one Step:
$file = “c:\folder\Prefix_$((Get-Date).Tostring(“yyyy-MM-ddThh-mm-ss”)).txt”
greets
Peter Kriegel
http://www.admin-source.de
(Get-Date -Format s).Replace(‘:’,’-‘)
Same thing but shorter
# Get sortable date/time stamp in ISO-8601:2004 basic format “YYYYMMDDTHHMMSSZZZ” with no invalid file name characters.
$dateTimeStamp = [RegEx]::Replace( (Get-Date).AddDays($DateOffsetDays).ToString(‘yyyyMMdd\THHmmsszzz’), “[$([System.IO.Path]::GetInvalidFileNameChars())]”, ” )
Sorry, my last example included a date offset, so not an appropiate reponse. Here it is again answering the question more specifically. This creates a universal sortable date format, including the time zone offset of the server the script is ran from. This way you know exactly when it was used. For example: “20130327T152538-0600”. Though it appears odd, the ‘T’ in the middle is the date/time seperator.
# Get sortable date/time stamp in ISO-8601:2004 basic format “YYYYMMDDTHHMMSSZZZ” with no invalid file name characters.
$dateTimeStamp = [RegEx]::Replace( (Get-Date).ToString(‘yyyyMMdd\THHmmsszzz’), “[$([System.IO.Path]::GetInvalidFileNameChars())]”, ” )
As always, anyone can give me the same results in a better way, please share.