文件名中的Powershell提取编号

时间:2018-01-23 19:05:03

标签: powershell powershell-v3.0

文件名可以是:

1234_billing.txt
1234billling.txt
123_billing.txt
123billing.txt

如何在所有4个案例中提取唯一的数字? 我已经尝试了-split和$ _。BaseName.Substring()但似乎无法使其正确。

1 个答案:

答案 0 :(得分:1)

Assuming that the filenames are in the array variable $flist, the following will do the trick:

foreach ($file in $flist) {
    if ($file -match "\d+") {
        $matches.value
    }
}

The -match operator takes as its right operand a regex pattern; in this case we use the pattern \d+ to signal any non-zero number of consecutive digits. The operator returns either $true or $false, and stores the matched substring in $matches. There's more about the -match operator at Get-Help about_Operators, and everyone can use a handy reference for regular expressions.