在PowerShell错误消息中使用touch命令创建新文件 [英] Creating new file with touch command in PowerShell error message

查看:565
本文介绍了在PowerShell错误消息中使用touch命令创建新文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的桌面上有一个使用PowerShell创建的目录,现在我正在尝试在其中创建文本文件.

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

我确实将目录更改为新目录,然后键入touch textfile.txt.

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`

为什么它不起作用?我需要一直使用Git Bash吗?

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

推荐答案

如果在PowerShell中需要命令touch,则可以定义一个执行正确的事情的函数:

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

将函数放入您的配置文件,以便在您启动PowerShell时可用.

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

touch定义为别名(New-Alias -Name touch -Value New-Item)在这里不起作用,因为New-Item具有强制性参数-Type,并且您不能在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.

这篇关于在PowerShell错误消息中使用touch命令创建新文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆