Forum Discussion

pspBugs's avatar
pspBugs
Copper Contributor
May 14, 2022

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...
  • LainRobertson's avatar
    May 14, 2022

    pspBugs 

     

    Here's a three-line example on how you can do this. I've gone with the assumptions that:

     

    1. The prefix date format should be "yyyyMMdd_";
    2. 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

Resources