Search code examples
regexbatch-filepowershellbatch-rename

remove date from filename programmatically


I'm trying to find a solution to strip some dates out of filenames programmatically. My files have the following format:

net_20110909_servercleanup.pdf

or

net_servercleanup_20110909.pdf

I've used the solution posted below (found on Stack Overflow also) to update some of the filenames but I would ideally have one solution that could update all files in my directories. I'd like to strip the date and one of the underscores out so the final file looks like this:

net_servercleanup.pdf

I'd like to do this from a batch file or PowerShell. I've seen some solutions that accomplish something like this using RegEx but I don't know enough about them to create something that will work. Any suggestions on how to accomplish this?

$filelist = (get-childitem c:\folder | Where-Object {$_.mode -match "a"} | foreach-object      {$_.name})
foreach ($file in $filelist)
{
    $len = $file.length
    $newname = $file.substring(0,$len -13)
    $newname = $newname + '.txt'
    Rename-Item C:\folder\$file $newname
    clear-variable newname, len
}

Solution

  • PowerShell, untested but should work:

    $filelist = Get-ChildItem C:\folder | Where-Object {$_.Mode -match "a"} `
        | Foreach-Object {$_.FullName}
    
    foreach ($fullpath in $filelist)
    {
        $newpath = $fullpath -replace "_(19|20)[0-9]{6}"
        Rename-Item -Path $fullpath -NewName $newpath -WhatIf
    }
    

    The _(19|20)[0-9]{6} regular expression matches the following pattern: leading "_" followed by "19" or "20" and then any six digits. If you have file names where date does not strictly match your example, you may need to modify the regex to catch them all.

    The -WhatIf switch allows you to do a "dry run" i.e. test cmdlets like Remove-Item without actually performing any file operations. Remove it when everything looks OK and you are ready to proceed with actual renaming.