Windows equivalent of 'touch' (i.e. the node.js way to create an index.html)

后端 未结 19 2275
一整个雨季
一整个雨季 2020-11-28 00:47

On a windows machine I get this error

\'touch\' is not recognized as an internal or external command, operable program or batch file.

19条回答
  •  一向
    一向 (楼主)
    2020-11-28 01:18

    I'm surprised how many answers here are just wrong. Echoing nothing into a file will fill the file with something like ECHO is ON, and trying to echo $nul into a file will literally place $nul into the file. Additionally for PowerShell, echoing $null into a file won't actually make a 0kb file, but something encoded as UCS-2 LE BOM, which can get messy if you need to make sure your files don't have a byte-order mark.

    After testing all the answers here and referencing some similar ones, I can guarantee these will work per console shell. Just change FileName.FileExtension to the full or relative-path of the file you want to touch; thanks to Keith Russell for the COPY NUL FILE.EXT update:

    CMD w/Timestamp Updates

    copy NUL FileName.FileExtension

    This will create a new file named whatever you placed instead of FileName.FileExtension with a size of 0 bytes. If the file already exists it will basically copy itself in-place to update the timestamp. I'd say this is more of a workaround than 1:1 functionality with touch but I don't know of any built-in tools for CMD that can accomplish updating a file's timestamp without changing any of its other content.

    CMD w/out Timestamp Updates

    if not exist FileName.FileExtension copy NUL FileName.FileExtension

    Powershell w/Timestamp Updates

    if (!(Test-Path FileName.FileExtension -PathType Leaf)) {New-Item FileName.FileExtension -Type file} else {(ls FileName.FileExtension ).LastWriteTime = Get-Date}

    Yes, it will work in-console as a one-liner; no requirement to place it in a PowerShell script file.

    PowerShell w/out Timestamp Updates

    if (!(Test-Path FileName.FileExtension -PathType Leaf)) {New-Item FileName.FileExtension -Type file}

提交回复
热议问题