It looks like a bunch of the answers here don't account for file encoding.
I just ran into this problem, for various other reasons, but
echo $null > $file
$null > $file
both produce a UTF-16-LE file, while
New-Item $file -type file
produces a UTF-8 file.
For whatever reason fc > $file
and fc >> $file
, also seem to produce UTF-8 files.
Out-File $file -encoding utf8
gives you a UTF-8-BOM file, while
Out-File $file -encoding ascii
gives you a UTF-8 file. Other valid (but untested) encodings that Out-File supports are: [[-Encoding] {unknown | string | unicode | bigendianunicode | utf8 | utf7 | utf32 | ascii | default | oem}]. You can also pipe stuff to Out-File to give the file some text data to store, and also an -append flag. For example:
echo $null | Out-File .\stuff.txt -Encoding ascii -Append
this example does not update the timestamp for some reason, but this one does:
echo foo | Out-File .\stuff.txt -Encoding ascii -Append
Although it does have the side effect of appending "foo" to the end of the file.
If you are unsure about what encoding you have, I've found VS-Code has a nifty feature where at the bottom right hand corner it says what the encoding is. I think Notepad++ also has a similar feature.
@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. – jsalonen – 2017-09-21T08:04:21.800
A PowerShell-idiomatic implementation that almost has feature parity with the Unix
– mklement0 – 2019-11-07T20:25:36.477touch
utility: https://stackoverflow.com/a/58756360/453751
See Windows version of the Unix touch command & Windows equivalent of the Linux command 'touch'?
– amiregelz – 2012-11-07T19:32:01.5531Thanks. 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. – jsalonen – 2012-11-07T19:33:28.910
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. – yzorg – 2014-02-18T00:49:58.250
@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. – jsalonen – 2014-02-18T09:13:03.793@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. – yzorg – 2014-02-18T14:44:11.693@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. :) – yzorg – 2014-02-18T14:50:32.913