Brendan Gilman
Brendan Gilman

Reputation: 1

Replace Part of a File Name in Powershell

I have files that look like this:

2020-0517-example.pdf

2020-0412-example.pdf

2020-0607-example.pdf

I would like to rename the files to:

2020-0723-example.pdf

2020-0723-example.pdf

2020-0723-example.pdf

I would basically be replacing the dates to today's date while keeping the year and the suffix.

Upvotes: 0

Views: 127

Answers (2)

AdminOfThings
AdminOfThings

Reputation: 25041

If you want to add a bit of sanity checking to make sure you are dealing with dates, you can use pattern matching and then rename the partial date:

$date = Get-Date -Format MMdd
Get-ChildItem -Path <filepath> -File |
    Where Basename -match '^(?:19|20)\d\d-(?:0[1-9]|1[012])\d\d-' |
        Rename-Item -NewName { $_.Name -replace '(?<=^\d{4}-)\d{4}',$date } -whatif

Alternatively, you can parse the date string first to verify it using TryParseExact:

$date = Get-Date -Format MMdd
Get-ChildItem -Path <filepath> -File |
    Where Name -match '^\d{4}-\d{4}-' | Foreach-Object {
        if ([datetime]::TryParseExact($_.Name.Substring(0,9),'yyyy-MMdd',[System.Globalization.CultureInfo]::InvariantCulture,[System.Globalization.DateTimeStyles]::None,[ref]0)) {
            $FileParts = $_.Name -split '-',3
            Rename-Item -Path $_ -NewName ($FileParts[0],$date,$FileParts[2] -join '-') -WhatIf
       }
    }

You will need to remove the -WhatIf parameter for the rename operation to complete.

Explanation:

Using -split '-',3, we ensure that we are left with no more than three array elements. This provides a predictable number of indexes for putting the file name back together. [0] will be the year. [1] will be the month-day. [2] will be the remainder of the file name.

Please see the following for the -replace and -match regex details:

Regex -Match

Regex -Replace

Upvotes: 3

Filburt
Filburt

Reputation: 18092

You could split by "-" and stitch together with String.Format:

$filename = "2020-0517-example.pdf"
$today = Get-Date
$arr = $filename.Split("-")
$newname = "{0}-{1:MMdd}-{2}" -f $arr[0], $today, $arr[2]

Upvotes: 1

Related Questions