Search code examples
powershellbatch-rename

Using Rename-Item to make numeric identifiers & names consistent


I have several thousand file names delimited as such:

Last, First-000000-Title-MonYYYY.pdf

Probem 1: Some files conform to the 6-digit convention while others need leading zeroes for consistency.

Problem 2: Some names are entered with dashes (which are, problematically, delimiters) which need to be joined as such: Last-Last, First > LastLast, First

I'm able to perform a simple Rename-Item function for each file but have not been able to create a broader Get-ChildItem function taking into account the several iterations of file names to generate a consistent output.

Apologies for the entry-level question but I cannot seem to coherently draw together the required functions.


Solution

  • Based on your explanations:

    Set-Location -Path "C:\path" # replace this with actual path to where the files are
    
    $cFiles = Get-ChildItem -Filter "*.pdf" # Getting all PDFs in the folder
    
    foreach ($oFile in $cFiles) {
        $sName = $oFile.Name
        # This regex captures 1-5 digits number between two dashes.
        $sPattern = '(?:(?<=-))(\d{1,5})(?:(?=-))'
        if ($sName -match $sPattern) {
            # Extracting number.
            [UInt32]$iNumber = $sName -replace (".*" + $sPattern + ".*"), '$1'
            # Padding number with zeros.
            $sNumber = "{0:D6}" -f $iNumber
            # Updating filename string.
            $sName = $sName -replace $sPattern, $sNumber
        } else {
            # This regex captures 6 digits number between two dashes.
            $sPattern = '.*-(\d{6})-.*'
            # Extracting number.
            $sNumber = $sName -replace $sPattern, '$1'
        }
    
        # Splitting filename string on 6 digits number.
        $cParts = $sName -split $sNumber
        # Removing dashes from first/last names and re-assembling filename string.
        $sName = ($cParts[0] -replace '-') + '-' + $sNumber + $cParts[1]
    
        Rename-Item -Path $oFile.Name -NewName $sName
    }
    

    Tested on the following sample:

    Last, First-000000-Title-Jan1900.pdf
    One-Two, Three-123-Title-Feb2000.pdf
    Four, Five-Six-456-Title-Mar2010.pdf
    Seven-Eight, Nine-Ten-7890-Title-Sep2012.pdf
    

    May not work if there are more complicated cases.