How would I get the file with the maximum date?
BACKUP-20220114.BAK
BACKUP-20220118.BAK
BACKUP-20220120.BAK
How would I select the file with the largest date value? I tried just finding the maximum string, but alas strings are not compared that way in powershell.
ls BACKUP* | select-object -Property Name | Measure-Object -Maximum
Measure-Object : Cannot compare "@{Name=BACKUP-20221028.bak}" because it is not IComparable.
How do I imbue the string with an IComparable
?
CodePudding user response:
As per my comment.
(
$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
#>
If you insist on using Measure-Command -Maximum
, then a similar approach is:
(
Get-Content -path 'variable:\BackUpDates' |
ConvertFrom-Csv -Header BackUpDate |
Measure-Object -Property BackUpDate -Maximum
).Maximum
# Results
<#
BACKUP-20220120.BAK
#>