PowerShell for Windows Admins

Apr 3 2013   1:17PM GMT

Putting the date in a file name

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

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

 Comment on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to: