How to avoid using Unix touch command on Windows…

In my company we have a strange habit of using third party tools to do the most trivial things rather than using the native features.

A recent example of this is the use of the “Unix” touch command on Windows. It turns out it is quite simple to avoid having to install cygwin or an-other Unix command tools and just use a simple batch file or using the appropriate tasks in MsBuild or Ant.

The batch file solution, is not a perfect solution as I suspect if the file is very large the “copy to self” could take a while but for general developer use it works just fine.

So my touch.bat is simply…

Windows touch.bat

@echo off
for %%i in (%*) do (
  if exist %%i (
    echo Updating timestramp for file : %%i
    copy /b "%%i" +,,
  )

  if not exist %%i (
    echo Creating zero length file : %%i
    copy nul %%i
  )
)

If you are using msbuild, then it has a “Touch task” and similarly if you are using Ant it too has a Touch Task

Lastly if you are using powershell it can be done with a simple function:

function touch
{
  $file = $args[0]
  if($file -eq $null) {
    throw "No filename supplied"
  }

  if(Test-Path $file)
  {
    (Get-ChildItem $file).LastWriteTime = Get-Date
  }
  else
  {
    echo $null > $file
  }
}
This entry was posted in fun, Microsoft Visual Studio, Tips, Windows Batch. Bookmark the permalink.