在PowerShell错误消息中使用touch命令创建新文件

Ton*_*oni 9 git powershell

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

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

这是我收到的错误消息:

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`
Run Code Online (Sandbox Code Playgroud)

为什么不起作用?我是否必须一直使用Git Bash?

Ans*_*ers 16

如果您需要touchPowerShell中的命令,您可以定义一个执行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
  }
}
Run Code Online (Sandbox Code Playgroud)

将该功能放在您的配置文件中,以便在您启动PowerShell时它可用.

定义touch为别名(New-Alias -Name touch -Value New-Item)在此处不起作用,因为New-Item它具有必需参数,-Type并且您不能在PowerShell别名定义中包含参数.


Rya*_*ase 15

如果你使用的是Windows Powershell,Mac/Unix触摸的等效命令是:New-Item textfile.txt -type file.

  • 这并不严格。`touch` 将更新文件的时间戳(如果存在),而不影响其内容。如果文件存在,`New-Item` 将失败。 (3认同)

M23*_*395 14

在 power shell 中创建单个文件: ni textfile.txt

同时创建多个文件: touch a.txt,b.html,x.jslinux命令
ni a.txt,b.html,x.js是windows power shell命令


bri*_*ist 7

正如Etan Reisner所指出的,touch它不是Windows中的命令,也不是PowerShell中的命令.

如果您想快速创建一个新文件(看起来您对刚刚更新现有文件日期的用例不感兴趣),您可以使用以下命令:

$null > textfile.txt
$null | sc textfile.txt
Run Code Online (Sandbox Code Playgroud)

请注意,第一个将默认为Unicode,因此您的文件不会为空; 它将包含2个字节,即Unicode BOM.

第二个使用sc(别名Set-Content),在FileSystem上使用时默认为ASCII.

如果你使用一个空字符串(''""[String]::Empty)代替$null你,也会以换行符结束.


小智 6

如果您使用的是node,只需使用此命令即可安装touch。

npm install touch-cli -g


Jer*_*yal 5

这是touch具有更好的错误处理能力的方法:

function touch
{
    $file = $args[0]
    if($file -eq $null) {
        throw "No filename supplied"
    }

    if(Test-Path $file)
    {
        throw "file already exists"
    }
    else
    {
        # echo $null > $file
        New-Item -ItemType File -Name ($file)
    }
}
Run Code Online (Sandbox Code Playgroud)

添加此函数C:\Program Files\PowerShell\7\Microsoft.PowerShell_profile.ps1(如果不存在则创建此文件)。

像这样使用它:touch hey.js