The Computer Oracle

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

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Unforgiving Himalayas Looping

--

Chapters
00:00 Equivalent Of Linux `Touch` To Create An Empty File With Powershell
00:40 Accepted Answer Score 248
00:56 Answer 2 Score 212
01:21 Answer 3 Score 92
01:44 Answer 4 Score 29
02:05 Answer 5 Score 26
02:34 Thank you

--

Full question
https://superuser.com/questions/502374/e...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#windows #windows8 #powershell #powershell30

#avk47



ACCEPTED ANSWER

Score 248


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

echo $null >> filename



ANSWER 2

Score 212


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



ANSWER 3

Score 92


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



ANSWER 4

Score 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




ANSWER 5

Score 26


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!