小赖子的英国生活和资讯

Windows Powershell下touch命令的实现

阅读 桌面完整版

PowerShell 中的 touch 命令(兼容 Linux 风格)

如果你来自 Linux/macOS 环境,可能会很想念 touch 命令:当文件不存在时创建文件,存在时更新它的修改时间。PowerShell 本身并没有内置 touch 命令,但我们可以自己实现一个行为与 Unix 类似的版本(支持多个文件和通配符)。

本文提供一个实用的 touch 函数,你可以将其添加到 PowerShell Profile 中长期使用,同时包含示例和一些边界情况说明。

“touch” 应该具备的行为

在 Unix 系统中,touch 通常具备以下特性:

下面我们将在 PowerShell 中实现这种行为。

一次性使用的简单版本(单文件)

如果你只是临时使用一次,下面是一行实现“创建或更新时间”的最简写法(不会向文件追加换行):


if (Test-Path .\file.txt) { (Get-Item .\file.txt).LastWriteTime = Get-Date } else { New-Item -ItemType File -Path .\file.txt | Out-Null }

Linux 风格的 touch 函数(支持多个文件 + 通配符)

该函数具有以下特性:

默认情况下不会输出多余信息。


function touch { 
    [CmdletBinding()] 
    param( 
        [Parameter(Mandatory=$true, ValueFromRemainingArguments=$true)] 
        [string[]] $Path,

        # 可选:当父目录不存在时自动创建
        [switch] $MakeDirs
    )

    $now = Get-Date

    foreach ($p in $Path) {

        # 展开通配符(例如 *.txt),若无匹配则按字面路径处理
        $expanded = @(Get-ChildItem -LiteralPath $p -ErrorAction SilentlyContinue)

        if ($expanded.Count -gt 0) {
            foreach ($item in $expanded) {
                if ($item.PSIsContainer) {
                    continue  # 跳过目录(Unix 行为可不同,这里更安全)
                }
                $item.LastWriteTime = $now
            }
            continue
        }

        # 没有通配符匹配时,按普通路径处理
        if (Test-Path -LiteralPath $p) {
            $item = Get-Item -LiteralPath $p
            if (-not $item.PSIsContainer) {
                $item.LastWriteTime = $now
            }
            continue
        }

        # 创建文件(可选创建父目录)
        if ($MakeDirs) {
            $parent = Split-Path -Parent $p
            if ($parent -and -not (Test-Path -LiteralPath $parent)) {
                New-Item -ItemType Directory -Path $parent -Force | Out-Null
            }
        }

        New-Item -ItemType File -Path $p -Force | Out-Null
    }
}

使用示例

创建或更新时间一个文件:

touch .\hello.txt

同时操作多个文件:

touch .\a.txt .\b.txt .\c.txt

更新当前目录下所有 .log 文件:

touch *.log

在嵌套目录中创建文件,并自动创建目录:

touch .\logs\2026\app.log -MakeDirs

永久安装 touch(添加到 PowerShell Profile)

PowerShell 启动时会加载 Profile 脚本。你可以把上面的函数添加到 Profile 文件中。

打开(或创建)Profile 文件:

notepad $PROFILE

touch 函数粘贴进去,保存并重启 PowerShell

如果 Profile 被禁用,可以为当前用户启用:

Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned

可选:更接近 Linux 的使用体验

如果你希望使用更短的别名:

Set-Alias -Name t -Value touch

也可以把这行加入 Profile。

注意事项

目录处理:当前实现会跳过目录。如果你希望“touch 目录也更新时间”,可以删除 PSIsContainer 判断。

通配符:PowerShell 使用 Get-ChildItem 处理通配符。如果通配符没有匹配结果,函数会按普通路径创建该文件(符合大多数人的预期)。

不会修改文件内容:不同于 "" >> file 的做法,本函数不会向文件追加换行或改变文件内容。

英文:The touch command in Windows Powershell

强烈推荐

微信公众号: 小赖子的英国生活和资讯 JustYYUK

阅读 桌面完整版
Exit mobile version