I am surprised how many answers here are simply incorrect. If you donβt insert anything into the file, the file will be filled with something like ECHO is ON , and an attempt to map $nul to the file will literally put $nul in the file. Also, for PowerShell, repeating $null in a file does not actually result in a 0K file, but something encoded as UCS-2 LE BOM , which can lead to confusion if you need to make sure your files do not have byte order marks.,
After testing all the answers here and referring to some similar ones, I can guarantee that they will work for each console shell. Just change FileName.FileExtension to the full or relative path to the file you want to touch :
CMD
if not exist FileName.FileExtension(fsutil file CreateNew FileName.FileExtension 0) else (copy/b FileName.FileExtension +,)
This will create a new file with the name no matter what you put instead of FileName.FileExtension with a length of 0 bytes. It will not do anything with this file other than updating the timestamp if it already exists using the else copy operation, it seems, but probably not quite the way touch works. I would say that this is more of a workaround than 1: 1 functionality, but I donβt know of any built-in tools for CMD that could update the fileβs timestamp without changing any other content.
Powershell
if (!(Test-Path FileName.FileExtension -PathType Leaf)) {New-Item FileName.FileExtension -Type file} else {(ls FileName.FileExtension).LastWriteTime = Get-Date}
This has the same functionality as the CMD version. It will not link to the existing file except its timestamp, and will create a new empty file of what you decided to use instead of FileName.FileExtension . And yes, it will work in the console as a single line; no need to put it in a PowerShell script file.
What if I do not want to change the timestamp?
If you do not want to change the timestamp of an existing file, we can simply remove the else -clauses.
CMD
if not exist FileName.FileExtension fsutil file CreateNew FileName.FileExtension 0
Powershell
if (!(Test-Path FileName.FileExtension -PathType Leaf)) {New-Item FileName.FileExtension -Type file}
kayleeFrye_onDeck Nov 13 '18 at 1:34 2018-11-13 01:34
source share