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

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.

8

14 Answers

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

echo $null >> filename 
15

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 
7

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 } } 
6

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

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!

3

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).

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 
2

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.

2

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 
1
ac file.txt $null 

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

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.

1

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)
4

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)

The webpage 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.

You Might Also Like