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
LainRobertson
May 14, 2022Silver Contributor
It isn't difficult to add a date-based prefix, but you've provided two different formats in your example below (yyyyMMdd_ and ddMMyyyy_.) Which is your preference?
And are you sure you want the creation date, not the last modified date?
Cheers,
Lain