简体   繁体   中英

Powershell - modify Date and Time of a file to reflect its filename

I have had to recover a load of files from a memory card to my hdd. The names for the recovered files on my hdd are in the format "yyyymmdd_hhmmss.mp4", and do show the correct times & dates.

However, the date modified column for these recovered files shows quite a different date (in the format "dd/mm/yyyy hh:mm" (obviously the seconds show when viewing their properties) as I reside in the UK), and I would like these date modified stamps to reflect their filenames once again. I have started to write a PowerShell script to extract the date & time to variables, and this is what I've done so far:

foreach ($file in Get-ChildItem *.mp4)
{
    $yy = $file.Name.substring(0,4)
    $mm = $file.Name.substring(4,2)
    $dd = $file.Name.substring(6,2)
    $hh = $file.Name.substring(9,2)
    $min = $file.Name.substring(11,2)
    $ss = $file.Name.substring(13,2)
}

However, my experience with PS cannot write the date modified attribute to reflect the filename. Please could someone help me?

Kind regards,

Rob Hughes.

To set the "date modified" property, update the $file.LastWriteTime property. You can use [datetime]::ParseExact() to parse the date and time from the files name in a single operation.

foreach($file in Get-ChildItem -Filter *.mp4)
{
    $file.LastWriteTime = [datetime]::ParseExact($file.BaseName, 'yyyyMMdd_HHmmss', $null)
}

The value you want to change to update the 'Date Modified' field is called .LastWriteTime . Here's how you'd change that with your current code.

    foreach ($file in Get-ChildItem *.mp4)
    {
    $yy = $file.Name.substring(0,4)
    $mm = $file.Name.substring(4,2)
    $dd = $file.Name.substring(6,2)
    $hh = $file.Name.substring(9,2)
    $min = $file.Name.substring(11,2)
    $ss = $file.Name.substring(13,2)

   #Create a Date Time object based on the file name
   $date =  get-date -Year $YY -Month $MM -Day $DD -Hour $hh -Minute $min -Second $SS

   #Echo out to screen
   Write-Host "Setting $($file.BaseName) dateModified as $($Date.Date)"
   $file.LastWriteTime = $Date
    }

Making a DateTime object is by far the easiest way to do this. Big props to you OP for sussing out the good bits from the file name like that, well done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM