首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >属性"basename“中目录列表中最大的数字。

属性"basename“中目录列表中最大的数字。
EN

Stack Overflow用户
提问于 2021-01-27 15:01:39
回答 1查看 35关注 0票数 1

我希望在我的目录列表的属性"basename“中拥有最大的数字。我不明白为什么不管用。我在我的目录D:\Coala\global\修补程序中有从数字1到21的21个目录。

对于我的程序,最大值是9,而对我来说,最大值是21。

$max和$item.BaseName的循环"foreach“中都有"int”类型。

请给我什么解决办法?

代码语言:javascript
复制
 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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-01-27 15:23:41

得到这个结果的原因是,Basename属性是一个字符串--当我们按字母顺序排序时,27先于9 -2,如果在9之前(举个例子)。

获得数值最高的值的最简单方法可能是使用Sort-Object

代码语言:javascript
复制
Get-ChildItem -path $path0 |Sort-Object {[int]$_.BaseName} -Descending |Select-Object -First 1

如果要手动进行比较,请确保始终将已转换为数字类型的值作为左侧操作数传递:

代码语言:javascript
复制
$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
  }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65921769

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档