DEV Community

Cassidy Williams
Cassidy Williams

Posted on • Originally published at cassidoo.co on

Remaking the Linux "touch" command in PowerShell

I switch back and forth between Windows and Mac pretty regularly depending on what I’m working on (and sometimes between WSL and PowerShell on the same machine, what a time to be alive), and one thing that I always mess up in PowerShell on Windows is making a new file.

On Linux-based machines, you can run touch filename to make a new file, and on Windows, you can do ni filename, which works just as well.

But with all the context switching I do, I wanted to be able to do both to keep myself in the flow when running a bunch of things on the command line.

I added this to my PowerShell profile:

function touch {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$true, ValueFromPipeline=$true)]
        [string]$Path
    )
    process {
        if (Test-Path -LiteralPath $Path) {
            (Get-Item -LiteralPath $Path).LastWriteTime = Get-Date
        }
        else {
            New-Item -ItemType File -Path $Path
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

This lets you run touch as you normally would, and also lets you pipe file paths to it (like "cake.txt", "fish.txt" | touch)!

To add this to your PowerShell profile, run this:

notepad $PROFILE
Enter fullscreen mode Exit fullscreen mode

Paste the function in, and then back in your shell, run:

. $PROFILE
Enter fullscreen mode Exit fullscreen mode

Blammo, one less brain cell needs to be wasted in the future. There’s definitely other functions out there that could also be added to make PowerShell feel more like a Linux-based shell, but this is the one I use the most!

Toodles!

Top comments (0)