我希望在我的目录列表的属性"basename“中拥有最大的数字。我不明白为什么不管用。我在我的目录D:\Coala\global\修补程序中有从数字1到21的21个目录。
对于我的程序,最大值是9,而对我来说,最大值是21。
$max和$item.BaseName的循环"foreach“中都有"int”类型。
请给我什么解决办法?
Here is my code:
$path0="D:\Coala\global\patch\"
$Updates0 = Get-ChildItem -path $path0
foreach ($item in $Updates0) {
[int]$max=0
[int]$item.BaseName
if ($item.BaseName -gt $max) {
$max=$item.BaseName
}
}
write-host the max is $max
The output of my code is:
PS D:\powershell> d:\powershell\shell1.ps1
1
10
11
12
13
14
15
16
17
18
19
2
20
21
3
4
5
6
7
8
9
the max is 9发布于 2021-01-27 15:23:41
得到这个结果的原因是,Basename属性是一个字符串--当我们按字母顺序排序时,27先于9 -2,如果在9之前(举个例子)。
获得数值最高的值的最简单方法可能是使用Sort-Object
Get-ChildItem -path $path0 |Sort-Object {[int]$_.BaseName} -Descending |Select-Object -First 1如果要手动进行比较,请确保始终将已转换为数字类型的值作为左侧操作数传递:
$max = -1
foreach ($item in $Updates0) {
# Get a numerical value corresponding to the basename string
$numericalBasename = [int]$item.BaseName
# Use this (rather than the string) for comparison + assignment
if ($numericalBasename -gt $max) {
$max = $numericalBasename
}
}https://stackoverflow.com/questions/65921769
复制相似问题