Cannot get PowerShell to display the maximum date.Need Help Please!

Welcome Forums General PowerShell Q&A Cannot get PowerShell to display the maximum date.Need Help Please!

This topic contains 3 replies, has 4 voices, and was last updated by

 
Keymaster
2 years, 6 months ago.

  • Author
    Posts
  • #39329

    Participant
    Points: 0
    Rank: Member

    Hi All,

    In my script
    times.txt has the below content:
    Monday, May 16, 2016 9:08:09 AM
    Friday, May 20, 2016 11:26:50 AM

    $times=Get-Content c:\times.txt"
    $times|Measure -Maximum

    This gives the wrong max: Monday, May 16, 2016 9:08:09 AM
    The dates are :
    Monday, May 16, 2016 9:08:09 AM
    Friday, May 20, 2016 11:26:50 AM

    Please help me.

  • #39330

    Participant
    Points: 0
    Rank: Member

    If your Times.txt is in chronological order you can use

    $Times | Select -Last 1

    Or

    $Times[-1]

    They both tell it to get the last member of the array. But again, this requires them to be in chronological order.

  • #39331

    Participant
    Points: 26
    Rank: Member

    You will need to convert the data into a datetime first before you can get the maximum. I have included something here that does it:

    $times | foreach-object{
    get-date($_)
    } | Measure-Object -Maximum | select-object maximum
  • #39332

    Keymaster
    Points: 1,673
    Helping HandTeam Member
    Rank: Community Hero

    $times contains Strings, not Date/Time objects. You need to cast them as dates first.

    $times = Get-Content times.txt | ForEach { [datetime]$_ }

The topic ‘Cannot get PowerShell to display the maximum date.Need Help Please!’ is closed to new replies.