Equivalent of Linux `touch` to create an empty file with PowerShell
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
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!
Related videos on Youtube
jsalonen
Updated on September 18, 2022Comments
-
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 over 11 years
-
Admin over 11 yearsThanks. 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 about 10 yearsDownvoted 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 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 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 forpowershell 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 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 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 over 4 yearsA PowerShell-idiomatic implementation that almost has feature parity with the Unix
touch
utility: stackoverflow.com/a/58756360/45375
-
-
jsalonen over 11 yearsThis 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 over 11 yearsSorry it doesn't. It gives me something like
cmdlet Copy-Item at command pipeline position 1 Supply values for the following parameters:
-
Yash Agarwal over 11 yearsjust press enter , it will give some error but ignore that , your file will be created.
-
jsalonen over 11 yearsActually you are right, it works. However, it's annoying to work that way if you have to run this many times.
-
Mark Allen over 11 yearsAdd it to your $profile file. (Run notepad $profile to edit that file.)
-
jk. over 11 yearstouch is rather different than this if the file already exists
-
J Slick over 11 yearsThis will delete the contents of the file if it exists.
-
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 about 11 yearsThanks! What does
sc
mean? Edit: figured it out ("Set Content") -
Jayesh Bhoot over 10 yearsI think this is the best approach!
-
Jamie Schembri over 10 yearsThis 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 almost 10 yearsperhaps
echo $null >> filename
would be more similar to Unix touch. -
alirobe almost 9 yearsecho is unnecessary,
$null > filename
works great. -
riahc3 almost 9 yearsDoes this work for updating the timestamp of a folder?
-
riahc3 almost 9 yearsWithout using a variable?
-
J Slick almost 9 years@riahc3, use this:
(gi MyFolder).LastWriteTime = Get-Date
. You could use that for files too. -
mlt about 8 yearsThis writes 2 bytes of unicode BOM 0xFEFF for me.
-
Rahil Wazir almost 8 yearsHey, it changes the encoding to
UTF-16 LE
-
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 about 7 years
Set-Content -Path $file -value $null
does the job and it does not affect file encoding. Check also ss64 version oftouch
. -
Scott - Слава Україні about 7 yearsThe
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 theseVerbose
,Debug
, andWhatIf
flags, etc? -
Fimpen almost 7 yearsVery, 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 namesSet-File
orSet-LastWriteTime
or, my favorite,Update-File
. Also, I would recommendAdd-Content $file $null
instead ofecho $null > $file
. Finally, set an alias withSet-Alias touch Update-File
if you want to keep using the commandtouch
-
martixy almost 7 yearsImportant 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 over 6 yearsYes - 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 over 6 yearsThis is not idempotent
ni : The file 'x.js' already exists
-
Nick Cox over 6 yearsEven more pithy:
ni example.txt
-
Davos about 6 yearsThis method doesn't add the awful BOM bytes and the encoding happily appears to be UTF-8.
-
Davos about 6 yearsThe 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 usingTouch
. I launch git bash in a powershell by running& "c:\Program Files\git\bin\bash.exe"
-
jpaugh almost 6 yearsOne important difference between this answer and
New-Item
is that this updates the timestamp of existing files. -
alastairtree over 5 yearsOr 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 over 4 yearsSuggest adding this as the last line:
New-Alias -Name Touch Touch-File
-
The Fool over 4 yearsThis should be the accepted answer ans it is a cleaner approach than the accepted one.
-
shirish over 4 yearsFor some reason, I have to always import the module again and again, this shouldn't happen, right Import-Module ./Touch.psm1
-
mklement0 over 4 yearsIndeed, 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 thetouch
utility, this solution doesn't update the last-write timestamp if the file already exists. -
mklement0 over 4 yearsNice, but it's better to use
New-Item $file
instead ofecho $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 over 4 yearsYes, 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 withNew-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 over 4 yearsThis has a TOCTTOU race, the file could be created between the check and the action.
-
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 about 4 yearsGolfed some more to avoid the interactive dialog @NickCox:
ni -i file foo.txt
-
Nick Cox about 4 yearsAn idempotent equivalent would be
ac x.js $null
-
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. over 3 yearsIs 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 over 3 yearshow does this differ from touch?
-
Bala Ganesh about 3 yearsThanks! this is the best way