293

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.

jsalonen
  • 9,321

14 Answers14

258

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

echo $null >> filename
Yash Agarwal
  • 3,326
  • 5
    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
  • 23
    touch is rather different than this if the file already exists – jk. Nov 07 '12 at 22:46
  • 40
    echo is unnecessary, $null > filename works great. – alirobe May 30 '15 at 12:54
  • 27
    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
237

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
  • 5,193
  • 1
    Does this work for updating the timestamp of a folder? – riahc3 Jul 28 '15 at 06:31
  • 3
    @riahc3, use this: (gi MyFolder).LastWriteTime = Get-Date . You could use that for files too. – dangph Jul 28 '15 at 11:26
  • 41
    Even more pithy: ni example.txt – Nick Cox Dec 21 '17 at 01:03
  • 7
    This method doesn't add the awful BOM bytes and the encoding happily appears to be UTF-8. – Davos Mar 26 '18 at 10:33
  • 2
    Golfed some more to avoid the interactive dialog @NickCox: ni -i file foo.txt – enharmonic Mar 27 '20 at 20:59
  • This works good for files with only extensions (for example .npmrc) The echo $null approach did not worked – Kevin Oswaldo Sep 08 '22 at 12:41
  • 1
    @Davos - The file is empty which is, by logic, compliant with any encoding there is. What encoding your analysis comes up with depends solely on its preference settings (i.e. when your text editor tries UTF8 first, it will report it is UTF8). – andowero Mar 29 '23 at 08:11
94

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
    }
}
  • 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
  • 20
    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
  • 2
    Suggest adding this as the last line: New-Alias -Name Touch Touch-File – stimpy77 Oct 01 '19 at 04:33
  • 4
    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, but it doesn't seem to work. – It'sNotALie. Oct 14 '20 at 10:23
30

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!

29

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

  • 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
  • 39
    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
  • 4
    ...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
  • I think the answer should be properly edited with a "This will delete the file content" warning or even better, just replaced with not2qubit final one-liner. – AlexD Mar 05 '24 at 18:46
24

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
  • 29
  • 132
  • 175
12

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
9

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
  • 91
  • Set-Content -Path $file -value $null does the job and it does not affect file encoding. Check also ss64 version of touch. – 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
6
ac file.txt $null

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

8DH
  • 252
4

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
  • 141
  • 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

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.

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,210
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)