powershell 获取最大字符串

1bqhqjot  于 2022-11-29  发布在  Shell
关注(0)|答案(1)|浏览(119)

如何获取包含最大日期的文件?

BACKUP-20220114.BAK
BACKUP-20220118.BAK
BACKUP-20220120.BAK

我如何选择日期值最大的文件呢?我试着只找到最大的字符串,但是唉,在powershell中字符串不是这样比较的。

ls BACKUP* | select-object -Property Name | Measure-Object -Maximum
Measure-Object : Cannot compare "@{Name=BACKUP-20221028.bak}" because it is not IComparable.

如何用IComparable填充字符串?

sxpgvts3

sxpgvts31#

正如我的评论。

(
$BackUpDates = @'
BACKUP-20220114.BAK
BACKUP-20220118.BAK
BACKUP-20220120.BAK
'@  | 
ConvertFrom-Csv -Header BackupDetail
)

# Results
<#
BackupDetail       
------------       
BACKUP-20220114.BAK
BACKUP-20220118.BAK
BACKUP-20220120.BAK
#>

$BackUpDates | 
Sort-Object -Property BackupDetail -Descending
# Results
<#
BackupDetail       
------------       
BACKUP-20220120.BAK
BACKUP-20220118.BAK
BACKUP-20220114.BAK
#>

$BackUpDates | 
Sort-Object -Property BackupDetail -Descending | 
Select-Object -First 1
# Results
<#
BackupDetail       
------------       
BACKUP-20220120.BAK
#>

Get-Content -path 'variable:\BackUpDates' | 
ConvertFrom-Csv -Header BackUpDate | 
Sort-Object -Property BackUpDate -Descending |
Select-Object -First 1
# Results
<#
BackUpDate         
----------         
BACKUP-20220120.BAK
#>

如果坚持使用Measure-Command -Maximum,那么类似的方法是:

(
Get-Content -path 'variable:\BackUpDates' | 
ConvertFrom-Csv -Header BackUpDate | 
Measure-Object -Property BackUpDate -Maximum
).Maximum
# Results
<#
BACKUP-20220120.BAK
#>

相关问题