正如Lee Dailey 指出的那样,touch 既不是 PowerShell 命令也不是标准实用程序(外部程序)在 Windows 上;相比之下,在类 Unix 平台上touch is a standard utility 具有双重用途:
在PowerShell中没有等效命令(从PowerShell 7.2开始),但是你可以使用现有的命令分别实现(a)和(b),你可以编写自定义脚本或函数它以类似于 Unix touch 实用程序的方式提供 (a) 和 (b):
# Update the last-modified and last-accessed timestamps of existing file app.js
$file = Get-Item -LiteralPath app.js
$file.LastWriteTime = $file.LastAccessTime = Get-Date
# Create file app.js in the current dir.
# * If such a file already exists, an error will occur.
# * If you specify -Force, no error will occur, but the existing file will be
# *truncated* (reset to an empty file).
$file = New-Item app.js
注意:创建文件时,默认为0-byte文件,但可以通过-Value参数传递内容。
Jeroen Mostert 建议使用以下技术来实现 条件 性质
touch 实用程序的文件创建:
# * If app.js exists, leaves it untouched (timestamps are *not* updated)
# * Otherwise, create it.
Add-Content app.js $null
注意:
下一节指向一个自定义函数,它包含 (a) 和 (b),同时还提供 Unix touch 实用程序提供的附加功能。
一个名为 Touch-File 的自定义函数,它实现了 Unix touch 实用程序的大部分功能 - 它有几个选项可以提供超出所描述的默认值的其他行为以上 - 可从this MIT-licensed Gist获得。
假设您已经查看了链接代码以确保它是安全的(我可以亲自向您保证,但您应该始终检查),您可以直接下载并在当前会话中定义它,如下所示,它还提供了有关如何使其在以后的会话中可用:
irm https://gist.github.com/mklement0/82ed8e73bb1d17c5ff7b57d958db2872/raw/Touch-File.ps1 | iex
注意:Touch 不是 PowerShell 中的 approved verb,但它仍然被选中,
因为没有一个被批准的动词可以充分传达核心功能
这个命令。
示例调用:
# * If app.js exists, update its last-write timestamp to now.
# * Otherwise, create it (as an empty file).
Touch-File app.js