lit
lit

Reputation: 16236

Comparing LastWriteTime and CreationTime

If a file is created and written once, I am expecting that LastWriteTime is the same as CreationTime. This code appears to say it is not true. Is there greater precision stored with these timestamps? Is a ToString and comparison the only way?

PS 09:30  C:\src\t
>Get-ChildItem .\uu.txt | Select-Object -Property Name,LastWriteTime,CreationTime

Name   LastWriteTime       CreationTime
----   -------------       ------------
uu.txt 2019-08-09 09:23:25 2019-08-09 09:23:25


PS 09:30  C:\src\t
>Get-ChildItem .\uu.txt | ForEach-Object { $_.LastWriteTime -eq $_.CreationTime }
False

UPDATE:

I ended up with the following code. If the difference between LastWriteTime and CreationTime is less than one second, this assumes the file has not been updated since creation.

$CloseEnough = New-Timespan -Seconds 1
Get-ChildItem -File -Path 'C:\src\t' |
    Where-object { ($_.LastWriteTime - $_.CreationTime) -lt $CloseEnough }

Upvotes: 4

Views: 7695

Answers (2)

antonyoni
antonyoni

Reputation: 899

In Windows - the CreationTime is the time that the file was created on a disk partition, and the LastWriteTime is the time that the file content was updated.

So at file creation the LastWriteTime is the time the write finished, whereas creation time is the time the file was created. They're not the same. You can check by measuring the write time, which will roughly be the same as the difference between LastWriteTime and CreationTime:

$str = 1..10000 | % { "$_`n" } # list of values to write
Measure-Command { $str | Out-File test.txt }
Get-Item test.txt | % { New-TimeSpan $_.CreationTime $_.LastWriteTime }

However, if you move a file to a different partition/disk on your computer, the CreationTime will be updated, but because the content hasn't changed, the LastWriteTime won't be. So you end up in a situation where your CreationTime is later than your LastWriteTime. To check:

Copy-Item c:\test.txt d:\test.txt
Get-Item c:\test.txt, d:\test.txt | select FullName, CreationTime, LastWriteTime

Your LastWriteTime will remain the same, but the CreationTime will change.

Upvotes: 6

user6811411
user6811411

Reputation:

Even writing to a file takes some time, so there has to be a difference.

Check with:

> Get-Item .\uu.txt | ForEach-Object { $_.LastWriteTime - $_.CreationTime}

Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 0
Milliseconds      : 2
Ticks             : 27616
TotalDays         : 3,1962962962963E-08
TotalHours        : 7,67111111111111E-07
TotalMinutes      : 4,60266666666667E-05
TotalSeconds      : 0,0027616
TotalMilliseconds : 2,7616

Strangely above time was measured in Win10pro in a VirtualBox VM on a MAC-Host writing to a Gbit networked FreeNAS share.

A native Win10 Pc writing to a local RamDisk/SSD was much slower.

Upvotes: 1

Related Questions