Home > Mobile >  Need to Edit command to Delete files in S3 bucket older than 90 days using PowerShell(90days instead
Need to Edit command to Delete files in S3 bucket older than 90 days using PowerShell(90days instead

Time:09-16

$bucketname = "bucketname" $key = aws s3api list-object-versions --bucket $bucketname --output json --query 'Versions[?LastModified<=2022-08-26].{VID:VersionId, Obj:Key}' | ConvertFrom-Json Write-host "Removing desired Objects From: $bucketname" -foregroundcolor red Foreach ($output in $key) { $delete = aws s3api delete-object --bucket $bucketname --key ($output).Obj --version-id ($output).VID --output text $output.Obj }

CodePudding user response:

I don't have S3 to test the code but it should fit your needs.

$bucketname = "aws-a0189-use1-00-d-s3b-ia-test"
$date = (Get-Date).adddays(-90).ToString("yyyy-MM-dd") # 90 days ago
$query = 'Versions[?LastModified<=`'   $date   '`].{VID:VersionId, Obj:Key}'
$key = aws s3api list-object-versions --bucket $bucketname --output json --query $query  | ConvertFrom-Json
Write-host "Removing desired Objects From: $bucketname" -foregroundcolor red
Foreach ($output in $key)
    {
       $delete =  aws s3api delete-object --bucket $bucketname --key ($output).Obj --version-id  ($output).VID --output text
       $output.Obj 
    }

in my code I added line two and three. The line two ("$date...") gets the date in the required format a few days back - in this example 90 days. The line three defines the query and inserts the date in the query.

the line four was changed a bit to include the $query variable

CodePudding user response:

$bucketname = "bucket name" $date = (Get-Date).adddays(-2).ToString("yyyy-MM-dd") # 2 days ago $query = 'Versions[?LastModified<=' $date '].{VID:VersionId, Obj:Key}' $key = aws s3api list-object-versions --bucket $bucketname --output json --query $query | ConvertFrom-Json Write-host "Removing desired Objects From: $bucketname" -foregroundcolor red Foreach ($output in $key) { $delete = aws s3api delete-object --bucket $bucketname --key ($output).Obj --output text $output.Obj }

  • Related