Categories

The simple touch

A utility called touch has been used for many years to modify the creation, access or write time property on a file. The System.Io.FileInfo class enables us to do this. It gets easier because Get-ChildItem returns – guess what - System.Io.FileInfo

The following properties can be modified

CreationTime
LastAccessTime
LastWriteTime

We can create a function to do this

 

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028

function set-filetime{ 
[CmdletBinding()] 
param ( 
[parameter(Mandatory = $true,
 
           ValueFromPipeline
=$true,
 
           ValueFromPipelineByPropertyName
=$true)] 
[string]$path,
[datetime]$date = (Get-Date),
[switch]$creation,
[switch]$access,
[switch]$write
 
) 

PROCESS
{
 
if (Test-Path $path
) {
 
$file = Get-ChildItem -Path $path
  if ($creation){$file.CreationTime = $date
}
 
if ($access){$file.LastAccessTime = $date
}
 
if ($write){$file.LastWriteTime = $date
}
 }
 
else
 {
  
Throw "File $path not found"
 }

}
#process


}
New-Alias -Name touch -Value set-filetime

Setting an alias makes it less typing to use from the command line

Some examples of using it

touch -path d1.txt -creation -access -write                                                                                                   
touch -path d1.txt -write -date (get-date).AddDays(-30)                                                                                       
touch -path d1.txt -access -date (get-date).AddDays(-15)                                                                                      
touch -path d1.txt -creation -date (get-date).AddDays(-50)  

Leave a Reply