Creating empty text files and changing file timestamps using Windows Command Prompt & Powershell

Linux and UNIX have the touch command for changing the creation dates and times for files. However, it also will create empty text files for you as well. In fact, there are times when I feel the need to do this sort of thing on Windows too and the following command accomplishes the deed when run in a Command Prompt window:

type nul > command.bat

Essentially, null output is sent to a file that is created anew, command.bat in this case. Then, you can edit it in Notepad (or whatever is your choice of text editor) and add in what you need. This will not work in Powershell so you need another command for that:

New-Item command.bat -type file

This uses the New-Item command, which also can be used to create folders as well if you so desire. Then, the command becomes the following:

New-Item c:\commands -type directory

Note that file on the previous example has become directory and there is the -force option should you need to overwrite what already exists for some reason…

That other use of the UNIX/Linux touch command can be performed from the Command Prompt too and here is an example command:

copy /b file.txt +,,

The /b switch switches on binary behaviour for the copy command though that appears to be the default action anyway. The + operator triggers concatenation and ,, gets around not having a defined destination because you cannot copy a file over itself. If that were possible, then there would no need for special syntax for changing the date and time for a file.

For doing the same thing with Powershell, try the following:

(GetChildItem test.txt).LastWriteTime=Get-Date

The GetChildItem command has aliases of gci, dir and ls and the last two of these give away its essential purpose. Here, it is used to pick out the test.txt file so that its timestamp can be replaced with the current date and time returned by the Get-Date command. The syntax looks a little more complex even if it achieves the same end. Somehow, that touch command is easier to explain. Are Linux and UNIX that complicated after all?

Leave a Reply