Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating new file with touch command in PowerShell error message

Tags:

I have a directory on my desktop created using PowerShell, and now I'm trying to create a text file within it.

I did change directory to the new one, and typed touch textfile.txt.

This is the error message I get:

touch : The term 'touch' is not recognized as the name of a cmdlet, function, 
script file, or operable program. Check the spelling of the name, or if a path was 
included, verify that the path is correct and try again.

At line:1 char:1
+ touch file.txt
+ ~~~~~
+ CategoryInfo          : ObjectNotFound: (touch:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException`

Why is it not working? Will I have to use Git Bash all the time?

like image 631
Antoni Parellada Avatar asked Sep 08 '15 02:09

Antoni Parellada


People also ask

Does touch command work in PowerShell?

In Linux, the touch command is used to generate a new file. However, in PowerShell, this command does not work; so, alternatives are used. This creates a file or folder,​ depending on the extension given.

What is touch command in PowerShell?

The touch command is a standard command used in UNIX/Linux operating system which is used to create, change and modify timestamps of a file.

Which option can be used to create a new file in PowerShell?

Create files and folders with PowerShell To create new objects with Windows PowerShell, you can use the New-Item cmdlet and specify the type of item you want to create, such as a directory, file or registry key.


1 Answers

If you need a command touch in PowerShell you could define a function that does The Right Thing™:

function touch {
  Param(
    [Parameter(Mandatory=$true)]
    [string]$Path
  )

  if (Test-Path -LiteralPath $Path) {
    (Get-Item -Path $Path).LastWriteTime = Get-Date
  } else {
    New-Item -Type File -Path $Path
  }
}

Put the function in your profile so that it's available whenever you launch PowerShell.

Defining touch as an alias (New-Alias -Name touch -Value New-Item) won't work here, because New-Item has a mandatory parameter -Type and you can't include parameters in PowerShell alias definitions.

like image 91
Ansgar Wiechers Avatar answered Sep 23 '22 04:09

Ansgar Wiechers