Cassidy Williams

Software Engineer in Chicago

Cassidy's face

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

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

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

. $PROFILE

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!


View posts by tag

#advice #personal #musings #events #recommendation #learning #work #technical #project #meta