You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell如何提取固定命名格式文件名中的版本号

PowerShell中快速提取固定格式文件名的版本号方法

我有一批遵循project.customer.version-number.zip命名格式的文件,例如project.customer.1.1.889.zip。其中“project”“customer”及zip后缀固定不变,仅“version-number”部分会变化。目前通过多次Split-Path拆分再拼接的方式提取版本号,代码如下:

$1 = (Split-Path -Path $filePath -Leaf).Split(".")[2];
$2 = (Split-Path -Path $filePath -Leaf).Split(".")[3];
$3 = (Split-Path -Path $filePath -Leaf).Split(".")[4];
$version = $1 + "." + $2 + "." + $3

以下是几种更快捷的提取方法:

  • 基于数组切片与拼接
    先获取文件名,拆分后跳过固定前缀的前两个元素,排除最后一个扩展名相关元素,再拼接成版本号:

    $fileName = Split-Path -Path $filePath -Leaf
    $splitParts = $fileName.Split('.')
    $version = $splitParts[2..($splitParts.Count - 2)] -join '.'
    

    这种方式无需提前知道版本号的段数,只要前缀和后缀固定就能适配。

  • 正则表达式匹配(推荐)
    用正则直接捕获版本号部分,灵活性最高,不管版本号是2段还是多段都能准确提取:

    $fileName = Split-Path -Path $filePath -Leaf
    if ($fileName -match '^project\.customer\.(.*)\.zip$') {
        $version = $matches[1]
    }
    

    匹配逻辑:^project\.customer\.匹配固定前缀,(.*)捕获中间所有版本号内容,\.zip$匹配固定后缀,捕获到的内容会存在$matches[1]中。

  • 结合.NET Path类与字符串替换
    先去除文件扩展名,再去掉固定前缀,直接得到版本号:

    $fileNameWithoutExt = [System.IO.Path]::GetFileNameWithoutExtension($filePath)
    $version = $fileNameWithoutExt -replace '^project\.customer\.'
    

    这种方式代码简洁,利用内置方法处理路径,可读性强。

内容的提问来源于stack exchange,提问作者polo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 06:55:17