Touch This

One of the last tasks for the Active Directory Powershell book was to assemble all the script samples. When the book is available you’ll be able to download a zip file from SAPIENPress.com. One thing I wanted to do was to use the file time stamp as a versioning tool.

This is pretty easy to do by modifying the CreationTime property among others. I put together a simple function called Touch-File. The function takes a filename and datetime as parameters. Even though the function will likely be used in a pipeline, I wanted to add some code to verify the file exists.

$file=Get-Item $path -ea “silentlycontinue”

By setting the -errorAction parameter to silentlyContinue, PowerShell will continue in the event the file doesn’t exist. Then I can use an If statement to see if $file has a value.

if ($file) {
        Write-Host “Touching $path” -foregroundcolor Green

Once I know the file exists, I can easily change the CreationTime properties, among others:

$file.CreationTime=$touch

Here’s a script I used to update all my AD scripts that puts this function to work.

   1: #Touch-File.ps1
   2:  
   3: Function Touch-File {
   4:     Param([string]$path=$(Throw "You must specify the name of a file"),
   5:           [datetime]$touch=(Get-Date)
   6:           ) 
   7:  
   8:     #properties to change
   9:  
  10:     [datetime]$UTCTime=$touch.ToUniversalTime()
  11:     
  12:     $file=Get-Item $path -ea "silentlycontinue"
  13:     if ($file) {
  14:         Write-Host "Touching $path" -foregroundcolor Green
  15:         $file.CreationTime=$touch
  16:         $file.CreationTimeUtc=$UTCTime
  17:         $file.LastAccessTime=$touch
  18:         $file.LastAccessTimeUtc=$UTCTime
  19:         $file.LastWriteTime=$touch
  20:         $file.LastWriteTimeUtc=$UTCTime
  21:     }
  22:     else {
  23:         Write-Warning "Failed to find $path"
  24:         
  25:     }
  26:  
  27: }
  28:  
  29: dir c:\scripts\posh\ad\*.ps1 | foreach {
  30:   Touch-File $_ "8/1/2008 01:00:00"
  31:   }

Every file in C:\scripts\posh\ad is sent to the Touch-File function that sets the file date to “8/1/2008 01:00:00”. Not sure if you have a need for a function like this but I like to share.

Download my sample script here.