Search code examples
powershell

PowerShell and Regex to reformat dates in my filenames


I am very new to Powershell. Bear with me.

I have a big directory of markdown files. They are either of the format <name>MMDDYY.md or <name>MMDDYYYY.md I'd like to use Powershell to rename them all to be in MMDDYY format.

Because my files are all from the year 2024, this is actually quite simple:

Get-ChildItem -recurse . | Rename-Item -NewName {$_.Name -replace '2024','24'}

But obviously I can't run this once I have more diverse filenames. I'd like a more general solution which automatically determine which files use MMDDYYYY format, and then rename only those ones. I know I could use a regex like \D*\d{2}\d{2}\d{4}.[m][d], but I'm not sure how to incorporate that into my Powershell command.

How could I do this?


Solution

  • Filter for files matching the pattern <name>MMDDYYYY.md with Where-Object:

    Get-ChildItem -Filter *.md |
        Where-Object Name -Match '[0-9]{8}\.md$' |
        Rename-Item -NewName { $_.Name.Replace('2024','24') }
    

    If you want something that could handle years dynamically, you can use a more complex pattern:

    $files = @(
        'foobar10102024.md'
        'foobar10102023.md'
    )
    $files -replace '(?<=[0-9]{4})[0-9]{2}(?=[0-9]{2}\.md$)'
    
    # foobar101024.md
    # foobar101023.md
    

    In practice:

    Get-ChildItem -Filter *.md |
        Where-Object Name -Match '[0-9]{8}\.md$' |
        Rename-Item -NewName { $_.Name -replace '(?<=[0-9]{4})[0-9]{2}(?=[0-9]{2}\.md$)' }