Unix touch Command in Powershell

How to add an alias for the touch command in Powershell.

PowerShellWindows

The Unix command line is superior to PowerShell. Unix commands easily fit in the mind. PowerShell feels like it’s in the way. Creating a new file is a prime example:

In Unix

bash
touch name_of_your_file.txt

In Powershell

sql
New-Item -Path name_of_your_file.txt -ItemType File

So, let’s put the Unix touch command in PowerShell.

Step 1 — Open the Powershell $PROFILE

The PowerShell $PROFILE is a special environment variable that points to a script that runs at the start of every PowerShell session. You can use it to define custom functions. Find it’s location by typing:

bash
$PROFILE

into PowerShell. You’ll get an output like this:

makefile
C:\Users\Connor\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1

Open this file in the text editor of your choice.

Step 2 — Add the touch function

Add the following function to your profile:

bash
function touch {
    param([string]$file)

    if (Test-Path $file) {
        # Update the timestamp if the file exists
        Set-ItemProperty -Path $file -Name LastWriteTime -Value (Get-Date)
    }
    else {
        # Create a new file if it doesn't exist
        New-Item -Path $file -ItemType File
    }
}

Save the profile, go back to your terminal and run:

bash
. $PROFILE

This will reload your $PROFILE script and give you access to the function. Try it out with:

bash
touch oh_my_god_this_is_so_much_easier.txt

Final Words

There you go, about 2 minutes saved per infrequent file creation. Happy file creating! 📁