Friday, December 11, 2020

How To: Change the File Time for a Windows File

When using PowerShell in Windows, The Get-ChildItem (and other cmdlets) return objects of the type System.IO.FileInfo for files in the NTFS File system. Each of the returned objects contains six date/time objects:
  • CreationTime and CreationTimeUtc - the date/time that the file was created (in local time and UTC)
  • LastAccessTime and LastAccessTimeUtc - the date/time that the file was last accessed
  • LastWriteTime and LastWriteTimeUtc - the date/time that the file was last written
These properties allow you to check a file (or for that matter a folder) for when it was created and when it was last written to and read from. This is very useful to help IT Professionals to discover files that are underused and may be candidates for deletion. To cater for files being accessed in different time zones, the UTC variants provide time-zone proof times for comparison.

One challenge is that you may wish to change these times. There is no cmdlet that can change these times directly. Fortunately, there is a simple bit of PowerShell magic. Assume you have a file for which you wish to change date/times. 

Here is you can do it:

PSH [C:\Foo]: Remove-Item -Path C:\Foo\ -ea 0  
PSH [C:\Foo]: "FOO" | Out-File -Path C:\Foo\
PSH [C:\Foo]: #    Find file and display
PSH [C:\Foo]: $File = Get-ChildItem -Path c:\foo\
PSH [C:\Foo]: $File| Format-List -Property name,*time*

Name              :
CreationTime      : 11/12/2020 10:09:57
LastAccessTime    : 11/12/2020 10:09:57
LastAccessTimeUtc : 11/12/2020 10:09:57
LastWriteTime     : 11/12/2020 10:09:57
LastWriteTimeUtc  : 11/12/2020 10:09:57

PSH [C:\Foo]: #    Get new date
PSH [C:\Foo]: $NewDate = Get-Date -Date '14/08/1950'
PSH [C:\Foo]: #    Change the date
PSH [C:\Foo]: $File.CreationTime      = $NewDate
PSH [C:\Foo]: $File.CreationTimeUTC   = $NewDate
PSH [C:\Foo]: $File.LastAccessTime    = $NewDate
PSH [C:\Foo]: $File.LastACcessTimeUTC = $NewDate
PSH [C:\Foo]: $File.LastWriteTime     = $NewDate
PSH [C:\Foo]: $File.LastWriteTimeUTC  = $NewDate
PSH [C:\Foo]: #    Recheck file to see changed date/time
PSH [C:\Foo]: $File = Get-ChildItem -Path C:\Foo\
PSH [C:\Foo]: $File| Format-List -Property Name,*Time*

Name              :
CreationTime      : 14/08/1950 01:00:00
CreationTimeUtc   : 14/08/1950 00:00:00
LastAccessTime    : 14/08/1950 01:00:00
LastAccessTimeUtc : 14/08/1950 00:00:00
LastWriteTime     : 14/08/1950 01:00:00
LastWriteTimeUtc  : 14/08/1950 00:00:00

No comments: