Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 783
user3791201 Avatar asked Oct 18 '25 04:10

user3791201


2 Answers

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)
}
like image 60
Mathias R. Jessen Avatar answered Oct 20 '25 22:10

Mathias R. Jessen


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.

like image 45
FoxDeploy Avatar answered Oct 20 '25 20:10

FoxDeploy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!