首页 > 解决方案 > 使用 Powershell 删除 s3 Bucket 中超过 14 天的文件

问题描述

我正在尝试编写一个脚本来使用 PowerShell 删除超过 14 天的文件,但我的脚本会删除在我的 s3 存储桶中创建的每个文件。

我的脚本有什么问题吗?

#set a bucket name
$bucket = "neb-migration/ms-sql/"

#set the expiration date of files
$limit_date = (Get-Date).AddDays(-14)

#get all the files
$files = aws s3 ls "$($bucket)"

#extract the file name and date
$parsed = $files | ForEach-Object { @{ date = $_.split(' ')[0] ; fname = $_.split(' ')[-1] } }

#filter files older than $limit_date
$filtred = $parsed | Where-Object { ![string]::IsNullOrEmpty($_.date) -and [datetime]::parseexact($_.date, 'yyyy-MM-dd', $null) -ge  $limit_date }

# #remove filtered files
$filtred | ForEach-Object { aws s3 rm "s3://$($bucket)$($_.fname)" }

标签: amazon-web-servicespowershellamazon-s3

解决方案


推荐阅读