0

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?

1
  • Based on what you are showing, why not just sort descending and select the first one? (edited) Commented Nov 15, 2022 at 3:58

1 Answer 1

1

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
#>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.