Skip to content

PowerShell: Creation date into filenames

G5th August 2016

CNo Comments


Insert a file’s creation date into its file name using a simple piece of PowerShell scripting.

Let’s say that you want to use a PowerShell script to append the creation date of a series of files to those files’ names (for instance, to replace IMG_2479.jpg with 20160805_2479.jpg). This is an easy job for PowerShell, but there are a couple of traps.

Many people recommend using the Get-Date function, but this is problematic because it will insert today’s date:

Get-ChildItem -path "c:/path/to/files/" -recurse -include @("*.jpg") | rename-item -newname { $  -replace "IMG",$(get-date -Format yyyyMMdd)}

This is fine if you’re processing the files on the same day that they’re created. But what if you’re not?

A better approach is to use the CreationTime function, which turns the file’s creation date into a string (in this case, the format is yyyyMMdd but this can be customised). This is then inserted into the file name.

Get-ChildItem -path "c:/path/to/files/" -recurse -include @("*.jpg") | rename-item -newname { $  -replace "IMG",($_.CreationTime.toString("yyyyMMdd"))}

This code can be used with files of any type (just remove -include @("*.jpg")).

It is very important to note that if a file was copied or moved after the creation date, the CreationTime will return the date that the file was copied. To get around this, files should be moved or copied using robocopy rather than Windows Explorer if this is likely to be a problem. Robocopy will preserve all original meta information about a file.

Note, too, that the CreationTime returns the creation time of the file, which may be independent of when a photo was actually taken in the case of image files. EXIF data is not involved in this process.



No comments have yet been submitted. Be the first!

Have your say:

The following HTML is permitted:
<a href="" title=""> <b> <blockquote cite=""> <code> <em> <i> <q cite=""> <strike> <strong>

Comments will be published subject to the Editorial Policy.