Powershell Rename Multiple Files with LastWriteTime Prefix

This script should do exactly what you want

  • Search recursively from a root directory
  • Exclude files with existing "yyyyMMdd " file name prefix
  • Rename the files not excluded above with ""yyyyMMdd " file name prefix based on their specific LastWriteTime

Warning: You should test this script first because renaming could be dangerous. Remove the # in front of Rename-Itemafter you have verified that only intentional files will be renamed.

Long version

$folder = "C:\somefolder"
$files = get-childitem -path $folder -recurse | where { -not $_.PSIsContainer }
[datetime]$dirDate = New-Object DateTime

foreach ($file In $files) {

    $strDate = $file.Name.substring(0,8)

    if (-Not [DateTime]::TryParseExact($strDate, "yyyyMMdd", 
        [System.Globalization.CultureInfo]::InvariantCulture, 
        [System.Globalization.DateTimeStyles]::None, [ref]$dirDate)) {

        $newName = $file.lastwritetime.tostring("yyyyMMdd ") + $file.name
        echo $newName
        #Rename-Item -path $file.Fullname -newname $newName
    }   
}

Short version

[datetime]$dirDate = New-Object DateTime

dir "C:\somefolder" -r | ? { ! $_.PSIsContainer } | % {          

    if ( ! [DateTime]::TryParseExact($_.Name.substring(0,8), "yyyyMMdd", 
        [System.Globalization.CultureInfo]::InvariantCulture, 
        [System.Globalization.DateTimeStyles]::None, [ref]$dirDate)) {

        $newName = $_.lastwritetime.tostring("yyyyMMdd ") + $_.name
        echo $newName
        #Ren $_.Fullname $newName
    }
}

Used stackoverflow answers

  • [DateTime]::TryParseExact to test if the first 8 characters can be a valid date
  • $_.lastwritetime.tostring("yyyyMMdd ") to format the lastwrite stamp

Tags:

Powershell