Equivalent of Linux `touch` to create an empty file with PowerShell

310,777

Solution 1

Using the append redirector ">>" resolves the issue where an existing file is deleted:

echo $null >> filename

Solution 2

To create a blank file:

New-Item example.txt

Note that in old versions of PowerShell, you may need to specify -ItemType file .

To update the timestamp of a file:

(gci example.txt).LastWriteTime = Get-Date

Solution 3

Here is a version that creates a new file if it does not exist or updates the timestamp if it does exist.

Function Touch-File
{
    $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
    }
}

Solution 4

In PowerShell you can create a similar Touch function as such:

function touch {set-content -Path ($args[0]) -Value ($null)} 

Usage:

touch myfile.txt

Source

Solution 5

There are a bunch of worthy answers already, but I quite like the alias of New-Item which is just: ni

You can also forgo the file type declaration (which I assume is implicit when an extension is added), so to create a javascript file with the name of 'x' in my current directory I can simply write:

ni x.js

3 chars quicker than touch!

Share:
310,777

Related videos on Youtube

jsalonen
Author by

jsalonen

Updated on September 18, 2022

Comments

  • jsalonen
    jsalonen over 1 year

    Is there an equivalent of touch in PowerShell?

    For instance, in Linux I can create a new empty file by invoking:

    touch filename
    

    On Windows this is pretty awkward -- usually I just open a new instance of Notepad and save an empty file.

    So is there a programmatic way in PowerShell to do this?

    I am not looking to exactly match behaviour of touch, but just to find the simplest possible equivalent for creating empty files.

    • Admin
      Admin over 11 years
    • Admin
      Admin over 11 years
      Thanks. I looked at them, but most of the answer focus on command-prompt. I'd like to have a PowerShell solution that doesn't require me to install new applications.
    • Admin
      Admin about 10 years
      Downvoted the question - both features are only a few more lines of code, just implement both, not just half, esp. when the missing half other command is so dangerous.
    • Admin
      Admin about 10 years
      @yzorg: What do you mean by both features? I was only asking how to create an empty file in PS the way you can do with touch in Linux.
    • Admin
      Admin about 10 years
      @jsalonen Use *nix touch on an existing file it will update the last write time without modifying the file, see the links from @amiregelz. This question has a high google ranking for powershell touch, I wanted to alert copy/paste-ers that just this half of it can destroy data, when *nix touch doesn't. See @LittleBoyLost answer that handles when the file already exists.
    • Admin
      Admin about 10 years
      @jsalonen IOW if you reword the question to 'how to create an empty file in powershell' I'd remove my downvote, but leave *nix touch command out of it. :)
    • Admin
      Admin over 6 years
      @LưuVĩnhPhúc Clarified the question. I am not looking for feature-complete equivalent of touch, just the matching behaviour for creating empty files.
    • Admin
      Admin over 4 years
      A PowerShell-idiomatic implementation that almost has feature parity with the Unix touch utility: stackoverflow.com/a/58756360/45375
  • jsalonen
    jsalonen over 11 years
    This is great, thanks! Just what I wanted! Any ideas how I could install this function into the PowerShell so that it loads automatically when I start the shell?
  • jsalonen
    jsalonen over 11 years
    Sorry it doesn't. It gives me something like cmdlet Copy-Item at command pipeline position 1 Supply values for the following parameters:
  • Yash Agarwal
    Yash Agarwal over 11 years
    just press enter , it will give some error but ignore that , your file will be created.
  • jsalonen
    jsalonen over 11 years
    Actually you are right, it works. However, it's annoying to work that way if you have to run this many times.
  • Mark Allen
    Mark Allen over 11 years
    Add it to your $profile file. (Run notepad $profile to edit that file.)
  • jk.
    jk. over 11 years
    touch is rather different than this if the file already exists
  • J Slick
    J Slick over 11 years
    This will delete the contents of the file if it exists.
  • Nathan Hartley
    Nathan Hartley about 11 years
    +1 for the most Powershell-ish way to change LastWriteTime on a file (which is what I needed), though the question focused on the new file creation feature of the touch command.
  • jsalonen
    jsalonen about 11 years
    Thanks! What does sc mean? Edit: figured it out ("Set Content")
  • Jayesh Bhoot
    Jayesh Bhoot over 10 years
    I think this is the best approach!
  • Jamie Schembri
    Jamie Schembri over 10 years
    This is the correct answer for replicating the Unix touch program (albeit with a different name), but the question is oriented to simply creating a new file.
  • Nathan
    Nathan almost 10 years
    perhaps echo $null >> filename would be more similar to Unix touch.
  • alirobe
    alirobe almost 9 years
    echo is unnecessary, $null > filename works great.
  • riahc3
    riahc3 almost 9 years
    Does this work for updating the timestamp of a folder?
  • riahc3
    riahc3 almost 9 years
    Without using a variable?
  • J Slick
    J Slick almost 9 years
    @riahc3, use this: (gi MyFolder).LastWriteTime = Get-Date . You could use that for files too.
  • mlt
    mlt about 8 years
    This writes 2 bytes of unicode BOM 0xFEFF for me.
  • Rahil Wazir
    Rahil Wazir almost 8 years
    Hey, it changes the encoding to UTF-16 LE
  • Bender the Greatest
    Bender the Greatest over 7 years
    @mlt Redirecting to a file in Powershell does write the BOM, so this technique will also write the BOM as well. This question explains how to write a file in PS without the BOM (it is hamhanded I know): stackoverflow.com/questions/5596982/…
  • Anton Krouglov
    Anton Krouglov about 7 years
    Set-Content -Path $file -value $null does the job and it does not affect file encoding. Check also ss64 version of touch.
  • Scott - Слава Україні
    Scott - Слава Україні about 7 years
    The New-Item command has been offered in four previous answers.  You have provided a 20-line wrapper for it.  Can you explain a bit more clearly what advantage your solution has over the earlier ones?  For example, what are these Verbose, Debug, and WhatIf flags, etc?
  • Fimpen
    Fimpen almost 7 years
    Very, very tiny quibble: While Touch-File conforms to the Verb-Noun naming convention of PS, Touch is not an "approved" verb (not that it's a significant requirement: msdn.microsoft.com/en-us/library/ms714428.aspx). File is fine, btw. I recommend the names Set-File or Set-LastWriteTime or, my favorite, Update-File. Also, I would recommend Add-Content $file $null instead of echo $null > $file. Finally, set an alias with Set-Alias touch Update-File if you want to keep using the command touch
  • martixy
    martixy almost 7 years
    Important note: Many unix tools don't deal with BOM. This includes git for example(even on windows). You're gonna have problems if you use files created in this manner with tools that don't recognize BOMs. e.g. you try to create your .gitignore using this command and wonder why it won't work. BOM is the reason.
  • TheHans255
    TheHans255 over 6 years
    Yes - this method actually writes some bytes to the file. Node.js can't deal with those bytes either, creating a syntax error at the start of the file.
  • Zombo
    Zombo over 6 years
    This is not idempotent ni : The file 'x.js' already exists
  • Nick Cox
    Nick Cox over 6 years
    Even more pithy: ni example.txt
  • Davos
    Davos about 6 years
    This method doesn't add the awful BOM bytes and the encoding happily appears to be UTF-8.
  • Davos
    Davos about 6 years
    The answer using New-Item looks like it doesn't set the BOM and the encoding is UTF-8. But lately I've just been running the Linux Subsystem for windows, or just running git bash on windows and using Touch. I launch git bash in a powershell by running & "c:\Program Files\git\bin\bash.exe"
  • jpaugh
    jpaugh almost 6 years
    One important difference between this answer and New-Item is that this updates the timestamp of existing files.
  • alastairtree
    alastairtree over 5 years
    Or the safe version that does not clear out existing file contents function touch { if((Test-Path -Path ($args[0])) -eq $false) { set-content -Path ($args[0]) -Value ($null) } }
  • stimpy77
    stimpy77 over 4 years
    Suggest adding this as the last line: New-Alias -Name Touch Touch-File
  • The Fool
    The Fool over 4 years
    This should be the accepted answer ans it is a cleaner approach than the accepted one.
  • shirish
    shirish over 4 years
    For some reason, I have to always import the module again and again, this shouldn't happen, right Import-Module ./Touch.psm1
  • mklement0
    mklement0 over 4 years
    Indeed, Windows PowerShell unexpectedly creates a 2-byte file with the UTF-16LE BOM if filename doesn't exist yet. Fortunately, this is a no longer a problem in PowerShell Core, which generally defaults to (BOM-less) UTF-8 and produces a truly empty file. However, unlike the touch utility, this solution doesn't update the last-write timestamp if the file already exists.
  • mklement0
    mklement0 over 4 years
    Nice, but it's better to use New-Item $file instead of echo $null > $file, because the latter will create a 2-byte file with the UTF-16LE BOM in Windows PowerShell (but no longer in PowerShell Core).
  • mklement0
    mklement0 over 4 years
    Yes, in Windows PowerShell $null > $file unfortunately creates a 2-byte file with the UTF-16LE encoding; fortunately, in PowerShell Core you now get a truly empty file, as you do with New-Item in both editions. It is not meaningful to speak of a truly empty file (length of 0 bytes) as having a specific character encoding, such as UTF-8, however. Character encoding is only meaningful with respect to content (which is missing here), and, more specifically, with respect to text content.
  • poizan42
    poizan42 over 4 years
    This has a TOCTTOU race, the file could be created between the check and the action.
  • SilverbackNet
    SilverbackNet about 4 years
    @shirish You need to import modules every session, yes, unless you put it in a folder in the PSModulePath. (Or add its folder to PSModulePath.)
  • enharmonic
    enharmonic about 4 years
    Golfed some more to avoid the interactive dialog @NickCox: ni -i file foo.txt
  • Nick Cox
    Nick Cox about 4 years
    An idempotent equivalent would be ac x.js $null
  • not2qubit
    not2qubit over 3 years
    ...and the final one-liner version that can also handle directories: function touch {if((Test-Path -Path ($args[0])) -eq $false) {Set-Content -Path ($args[0]) -Value ($null)} else {(Get-Item ($args[0])).LastWriteTime = Get-Date } }
  • It'sNotALie.
    It'sNotALie. over 3 years
    Is there any way for this to implicitly make the folder structure? Add-Content -Force would seem like it works judging by the docs, but it doesn't seem to work.
  • Nicholas Saunders
    Nicholas Saunders over 3 years
    how does this differ from touch?
  • Bala Ganesh
    Bala Ganesh about 3 years
    Thanks! this is the best way