Forum Discussion
pspBugs
May 14, 2022Copper Contributor
Rename files to get the year, month and day of the creation in front of the file?
Hi all, I am a trainee and need to make some changes to the file naming convention. There are tens of thousands of files in the filesystem and it would be a long day to do it all manually. So my qu...
- May 14, 2022
Here's a three-line example on how you can do this. I've gone with the assumptions that:
- The prefix date format should be "yyyyMMdd_";
- You do indeed want the creation date used in the prefix, not the last modified date.
$ParsedDate = [datetime]::MinValue; $Path = "D:\Data\SomePath"; Get-ChildItem -File -Path $Path -Recurse | Where-Object { (-not [regex]::IsMatch($_.Name, "^\d{8}_", [System.Text.RegularExpressions.RegexOptions]::IgnoreCase)) -or (-not [datetime]::TryParseExact($_.Name.Substring(0, 8), "yyyyMMdd", [cultureinfo]::CurrentCulture, [System.Globalization.DateTimeStyles]::None, [ref] $ParsedDate)) } | ForEach-Object { Rename-Item -Path ($_.FullName) -NewName "$($_.CreationTime.ToString("yyyyMMdd"))_$($_.Name)"; }
Cheers,
Lain
Keith80s
Copper Contributor
This is working perfectly. If I want to add the hours and minutes in 24hr to the prefix, like 202303271430 for a file created at 14:30 today. Would that be easy to work in? tried to just put hhmm after the tostring but that's actually putting it in as 202303270230. Must be something about 12 vs 24 hr format.
Looks like you have something smart in there to ignore files already with the prefix added.
LainRobertson
Mar 27, 2024Silver Contributor
Just be aware that the special format characters are case-sensitive. For example:
Format string | Meaning |
hh | Two-digit hour using 12-hour clock. |
HH | Two-digit hour using 24-hour clock. |
Months (MM) and minutes (mm) is another one to be wary of.
You can find the full reference here:
Cheers,
Lain