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

查看:63
本文介绍了在 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天全站免登陆