Get most recent file from AWS s3 ls command

Welcome Forums General PowerShell Q&A Get most recent file from AWS s3 ls command

This topic contains 1 reply, has 2 voices, and was last updated by

 
Participant
1 month ago.

  • Author
    Posts
  • #170896

    Participant
    Topics: 1
    Replies: 0
    Points: 11
    Rank: Member

    Hi All,

    I'm completely new to powershell and don't have much experience working on Windows servers so please forgive me if this is a simple problem. The server has the AWS CLI installed and I need to sort the ls command by date and get the most recent file in the bucket. The command aws s3 ls s3://mybucket/myfolder/ outputs a listing like so with no headers:

    2018-01-18 09:04:02 0
    2018-01-18 11:00:33 7428 review-logo-btj-100.jpg
    2018-01-18 10:58:36 5860 review-logo-dilve-100.jpg

    I've tried piping the output to Sort Date -Descending but that has no affect on the output. I've managed to successfully isolate the datetime part with a regex and "select-string" but I still don't seem to be able to sort it properly.

    All that said, I was hoping somebody could help me find the best way to get the most recent file from a listing like that.

    Thanks in advance!
    Marty

  • #171208

    Participant
    Topics: 0
    Replies: 2
    Points: 6
    Rank: Member

    Marty,

    My first suggestion would be to install the AWS PowerShell module.  This will give you the ability to work with AWS services as PowerShell objects.  Your task could then be completed like this:

    Get-S3Object -BucketName bucketname | sort-object lastmodified | select -Last 1 | format-table -AutoSize -Property key,lastmodified

    This gets the contents of the bucket, sorts by the 'lastmodified' date, and selects the last entry.  For demonstration I then display it as a table.

    If you cannot load the AWS module, then maybe have the AWS CLI save as JSON and import the JSON in PowerShell.  Otherwise you are stuck with having to manipulate the AWS output as text in PowerShell, which just makes everything harder.

     

You must be logged in to reply to this topic.