267

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.

Peter Mortensen
  • 12,090
  • 23
  • 70
  • 90
jsalonen
  • 8,843
  • 14
  • 35
  • 40
  • 1
    See [Windows version of the Unix touch command](http://stackoverflow.com/questions/51435/windows-version-of-the-unix-touch-command) & [Windows equivalent of the Linux command 'touch'?](http://superuser.com/questions/10426/windows-equivalent-of-the-linux-command-touch) – amiregelz Nov 07 '12 at 19:32
  • 1
    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. – jsalonen Nov 07 '12 at 19:33
  • 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 Feb 18 '14 at 00:49
  • @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 Feb 18 '14 at 09:13
  • @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. – yzorg Feb 18 '14 at 14:44
  • 1
    @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 Feb 18 '14 at 14:50
  • 1
    @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 Sep 21 '17 at 08:04
  • A PowerShell-idiomatic implementation that almost has feature parity with the Unix `touch` utility: https://stackoverflow.com/a/58756360/45375 – mklement0 Nov 07 '19 at 20:25

14 Answers14

240

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

echo $null >> filename
Yash Agarwal
  • 3,120
  • 1
  • 14
  • 14
  • Sorry it doesn't. It gives me something like `cmdlet Copy-Item at command pipeline position 1 Supply values for the following parameters:` – jsalonen Nov 07 '12 at 19:37
  • just press enter , it will give some error but ignore that , your file will be created. – Yash Agarwal Nov 07 '12 at 19:38
  • Actually you are right, it works. However, it's annoying to work that way if you have to run this many times. – jsalonen Nov 07 '12 at 19:39
  • 1
    Ok. I have modified the ans , now it should do it in one line – Yash Agarwal Nov 07 '12 at 19:53
  • 4
    Also known as 'echo null>filename' from a command prompt, possibly a batch file. Cool to see the PowerShell version of it, thanks! – Mark Allen Nov 07 '12 at 21:11
  • 22
    touch is rather different than this if the file already exists – jk. Nov 07 '12 at 22:46
  • 1
    perhaps `echo $null >> filename` would be more similar to Unix *touch*. – Nathan May 21 '14 at 20:11
  • 30
    echo is unnecessary, `$null > filename` works great. – alirobe May 30 '15 at 12:54
  • 23
    This writes 2 bytes of unicode BOM 0xFEFF for me. – mlt Apr 20 '16 at 19:08
  • 1
    Hey, it changes the encoding to `UTF-16 LE` – Rahil Wazir Jul 04 '16 at 18:27
  • 1
    @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): http://stackoverflow.com/questions/5596982/using-powershell-to-write-a-file-in-utf-8-without-the-bom – codewario Jan 20 '17 at 20:07
  • 8
    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. – martixy Jul 31 '17 at 22:21
  • 1
    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. – TheHans255 Sep 29 '17 at 20:37
  • 1
    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"` – Davos Mar 26 '18 at 10:35
  • 1
    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 Nov 05 '19 at 12:37
195

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
dangph
  • 4,603
  • 4
  • 25
  • 31
89

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
    }
}
LittleBoyLost
  • 999
  • 6
  • 3
  • 4
    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. – Jamie Schembri Jan 04 '14 at 11:59
  • 18
    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: https://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` – Alan McBee May 25 '17 at 23:36
  • 1
    Suggest adding this as the last line: `New-Alias -Name Touch Touch-File` – stimpy77 Oct 01 '19 at 04:33
  • 3
    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 Nov 05 '19 at 12:43
  • 3
    This has a TOCTTOU race, the file could be created between the check and the action. – poizan42 Dec 27 '19 at 13:43
  • Is there any way for this to implicitly make the folder structure? `Add-Content -Force` would seem like it works judging by the [docs](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/add-content?view=powershell-7), but it doesn't seem to work. – It'sNotALie. Oct 14 '20 at 10:23
30

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

Ƭᴇcʜιᴇ007
  • 111,883
  • 19
  • 201
  • 268
  • 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 Nov 07 '12 at 19:34
  • 3
    Add it to your $profile file. (Run notepad $profile to edit that file.) – Mark Allen Nov 07 '12 at 21:12
  • 36
    This will delete the contents of the file if it exists. – dangph Jan 24 '13 at 06:31
  • 2
    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) } }` – alastairtree Sep 11 '18 at 16:51
  • 1
    ...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 } }` – not2qubit Sep 24 '20 at 08:05
24

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!

Jacob E. Dawson
  • 349
  • 2
  • 3
22

I prefer Format-Table for this task (mnemonic file touch):

ft > filename

To work with non-empty files you can use:

ft >> filename

I chose this because it is a short command that does nothing in this context, a noop. It is also nice because if you forget the redirect:

ft filename

instead of giving you an error, again it just does nothing. Some other aliases that will work are Format-Custom (fc) and Format-Wide (fw).

Zombo
  • 1
  • 24
  • 120
  • 163
11

I put together various sources, and wound up with the following, which met my needs. I needed to set the write date of a DLL that was built on a machine in a different timezone:

$update = get-date
Set-ItemProperty -Path $dllPath -Name LastWriteTime -Value $update

Of course, you can also set it for multiple files:

Get-ChildItem *.dll | Set-ItemProperty -Name LastWriteTime -Value $update
John Saunders
  • 574
  • 5
  • 17
8

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.

GarThor
  • 81
  • 1
  • 1
  • `Set-Content -Path $file -value $null` does the job and it does not affect file encoding. Check also [ss64 version of `touch`](https://ss64.com/ps/syntax-touch.html). – Anton Krouglov Mar 14 '17 at 15:18
  • 1
    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. – mklement0 Nov 05 '19 at 13:04
8

Open your profile file:

notepad $profile

Add the following line:

function touch {New-Item "$args" -ItemType File}

Save it and reload your $profile in order to use it straight away. (No need to close and open powershell)

. $profile

To add a new file in the current directory type:

touch testfile.txt

To add a new file inside 'myfolder' directory type:

touch myfolder\testfile.txt

If a file with the same name already exists, it won't be overidden. Instead you'll get an error.

I hope it helps

Bonus tip:

You can make the equivalent of 'mkdir' adding the following line:

function mkdir {New-Item "$args" -ItemType Directory} 

Same use:

mkdir testfolder
mkdir testfolder\testsubfolder
RafaelGP
  • 209
  • 2
  • 4
6
ac file.txt $null

Won't delete the file contents but it won't update the date either.

8DH
  • 242
  • 3
  • 9
3

I used the name "Write-File" because "Touch" isn't an approved PowerShell verb. I still alias it as touch, however.

Touch.psm1

<#
 .Synopsis
  Creates a new file or updates the modified date of an existing file.

 .Parameter Path
  The path of the file to create or update.
#>
Function Write-File {
    [CmdletBinding()]
    Param(
       [Parameter( Mandatory=$True, Position=1 )]
       [string] $Path,
       [switch] $WhatIf,
       [System.Management.Automation.PSCredential] $Credential
    )
    $UseVerbose = $PSCmdlet.MyInvocation.BoundParameters['Verbose'].IsPresent -eq $True
    $UseDebug = $PSCmdlet.MyInvocation.BoundParameters['Debug'].IsPresent -eq $True
    $TimeStamp = Get-Date
    If( -Not [System.Management.Automation.WildcardPattern]::ContainsWildcardCharacters( $Path ) ) {
        New-Item -ItemType:File -Verbose:$UseVerbose -Debug:$UseDebug -WhatIf:$WhatIf -Credential $Credential -Path $Path -ErrorAction SilentlyContinue -Confirm:$False | Out-Null
    }
    Set-ItemProperty -Verbose:$UseVerbose -Debug:$UseDebug -WhatIf:$WhatIf -Credential $Credential -Path $Path -Name LastWriteTime -Value:$TimeStamp -Confirm:$False | Out-Null
}

Set-Alias -Name touch -Value Write-File

Export-ModuleMember -Function Write-File
Export-ModuleMember -Alias touch

Usage:

Import-Module ./Touch.psm1
touch foo.txt

Supports:

  • Paths in other directories
  • Credential for network paths
  • Verbose, Debug, and WhatIf flags
  • wildcards (timestamp update only)
error
  • 131
  • 4
  • 1
    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? – Scott - Слава Україні Mar 23 '17 at 04:08
  • 1
    One important difference between this answer and `New-Item` is that this updates the timestamp of existing files. – jpaugh Jul 26 '18 at 15:49
  • For some reason, I have to always import the module again and again, this shouldn't happen, right Import-Module ./Touch.psm1 – shirish Nov 04 '19 at 21:15
  • 1
    @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.) – SilverbackNet Feb 28 '20 at 20:36
3

For the scenario you described (when the file doesn't exist), this is quick and easy:

PS> sc example.txt $null

However, the other common use of touch is to update the file's timestamp. If you try to use my sc example that way, it will erase the contents of the file.

Jay Bazuzi
  • 4,160
  • 6
  • 32
  • 41
3

to create an empty file in windows, the fastes way is the following:

fsutil file createnew file.name 0

The zero is filesize in bytes, so this is also useful to create large file (they will not be useful for testing compression since they do not contain actual data and will compress down to pretty much nothing)

Jon Carlstedt
  • 360
  • 1
  • 5
2

The webpage http://xahlee.info/powershell/PowerShell_for_unixer.html suggests:

new-item -type file [filename]

and this does indeed create a new file of size zero.

This doesn't perform the other function of Unix touch, namely to update the timestamp if filename already exists, but the question implies that the user just wants to create a zero-sized file interactively without resorting to Notepad.