使用 powershell 查找文件名中编号最大的文件

Finding a file that has highest number in the filename using powershell

对不起大家..我是 powershell 的新手。如果有人帮助解决以下情况,那就太好了:

我在文件夹 c:\test 中有几个文件

sample.x.x.1
sample.x.x.2
sample.x.x.3
sample.x.x.4
sample.x.x.5

我想在给定文件夹中找到名称中编号最大的文件的名称。在上面的例子中,5 是最大的数字,脚本应该 return 输出文件名为 sample.x.x.5

提前致谢!

用数字对文件名进行排序是一个很大的问题,因为有两种方法。第一个将它们设置为字母顺序。即,0, 1, 11, 111, 2,... 第二种使用自然顺序。即0, 1, 2, 11, 111...。这非常棘手,大约三分之一的程序员对此感到困惑。

已经有一个 good answer,我会这样引用它,

# Create files 1..5
for($i=1;$i -le 5; ++$i) { set-content sample.x.x.$i -Value $null } 

# Tricksy! Create file .10 to confuse asciibetic/natural sorting
set-content sample.x.x.10 -Value $null

ls # Let's see the files

    Directory: C:\temp\test

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----       2015-09-28     10:29              0 sample.x.x.1
-a----       2015-09-28     10:29              0 sample.x.x.10
-a----       2015-09-28     10:29              0 sample.x.x.2
-a----       2015-09-28     10:29              0 sample.x.x.3
-a----       2015-09-28     10:29              0 sample.x.x.4
-a----       2015-09-28     10:29              0 sample.x.x.5

# Define helper as per linked answer
$ToNatural = { [regex]::Replace($_, '\d+$', { $args[0].Value.PadLeft(20,"0") }) }

# Sort with helper and check the output is natural result
gci | sort $ToNatural -Descending | select -First 1

Directory: C:\temp\test

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----       2015-09-28     10:29              0 sample.x.x.10

字母排序。

PS C:\Users\Gebb> @("sample.x.x.1", "sample.x.x.5", "sample.x.x.11") | sort
sample.x.x.1
sample.x.x.11
sample.x.x.5

数值排序。

PS C:\Users\Gebb> @("sample.x.x.1", "sample.x.x.5", "sample.x.x.11") |
 sort -Property @{Expression={[Int32]($_ -split '\.' | select -Last 1)}}
sample.x.x.1
sample.x.x.5
sample.x.x.11

最大的数字。

PS C:\Users\Gebb> @("sample.x.x.1", "sample.x.x.5", "sample.x.x.11") |
 sort -Property @{Expression={[Int32]($_ -split '\.' | select -Last 1)}} |
 select -Last 1
sample.x.x.11