将Sort-Object 与计算属性(为每个输入对象评估的脚本块 ({ ... }) 一起使用,反映在$_ 中)如下:
# Sample input
$wholeContent =
[pscustomobject] @{ Name = 'Amma 10.0.0.1.zip'; Type = '...' },
[pscustomobject] @{ Name = 'Not a match' ; Type = '...' },
[pscustomobject] @{ Name = 'Amma 1.0.0.2.zip' ; Type = '...' },
[pscustomobject] @{ Name = 'Amma 2.1.2.3.zip' ; Type = '...' }
# Define the regex that matches the full name
# and captures the embedded version number in named capture group 'version'.
# Better to use '...' (single quotes) to define regexes, to prevent
# confusion with string expansion inside "..."
# Note the alternate syntax `<version>` instead of `'version'`.
$regex = '^Amma\s(?<version>(\d+\.){3}\d+)\.zip$'
# Filter by the line of interest, then sort by the extracted version number.
# Automatic variable $Matches is a hashtable that contains the results of
# the regex match, with entry 'version' containing the capture group's value.
# Casting to [version] ensures that version-appropriate sorting is used.
$wholeContent |
Where-Object { $_.Name -match $regex } |
Sort-Object { [version] ($_.Name -replace $regex, '${version}') }
注意这里需要匹配两次[1]:一次过滤感兴趣的行,再次通过@987654322提取嵌入的版本文本@。
注意:这里可以使用 -replace 和原始正则表达式,因为手头的正则表达式旨在匹配 whole 输入字符串,它允许将整个字符串替换为命名捕获组的值 (${version}) 仅产生后者;更详细的替代方法是使用另一个-match 操作通过$Matches 获取捕获组值:
$null = $_.Name -match $regex; $Matches['version']
上面的结果如下,表明只提取了感兴趣的行,并按版本号正确排序:
Name Type
---- ----
Amma 1.0.0.2.zip ...
Amma 2.1.2.3.zip ...
Amma 10.0.0.1.zip ...
[1] 虽然automatic $Matches variable 由-match 操作填充,原则上在后续管道段的脚本块中可用,允许访问匹配的结果操作,这里不能使用它,因为Sort-Object 必须是一个聚合 cmdlet;也就是说,它必须首先收集所有输入才能执行排序,此时在计算属性中使用$Matches仅包含最后一个输入对象的匹配项。支持>