amazon-web-services - 根据文件名删除 S3 对象
问题描述
我想从 S3 存储桶中删除所有包含关键字“更新”的文件。以下脚本将正确读出包含“更新”的文件,但该Remove-S3Object
命令将删除文件夹和文件夹中的所有文件,而不仅仅是包含“更新”的文件。
Set-AWSCredentials -AccessKey $s3AccessKey -SecretKey $s3SecretKey
$s3Contents = (Get-S3Object -BucketName "$s3Bucket" -Key "path/test/" -AccessKey $s3AccessKey -SecretKey $s3SecretKey).Key
Write-Host 'Here are the contents' $s3Contents -ForegroundColor Green
foreach($x in $s3Contents){
If($x -like '*Update*'){
(Remove-S3Object -BucketName "$s3Bucket" -Key "$x" -AccessKey $s3AccessKey -SecretKey $s3SecretKey).key
}
}
完整的文件路径如下:
Path/user/tier1/manual-retouch/test/File1.UPDATE.jpg
Path/user/tier1/manual-retouch/test/File2.Work.jpg
Path/user/tier1/manual-retouch/test/File3.jpg
如果我添加-Whatif
到Remove-S3Object
我得到以下回报:
What if: Performing the operation "Remove-S3Object (DeleteObjects)" on target "".
但是,没有-Whatif
powershell 脚本会提示我Are you sure you want to perform this action? Performing the operation "Remove-S3Object (DeleteObjects)" on target "".
4 次,并将删除所有文件和文件夹。
谁能指出我做错了什么?
解决方案
Amazon S3 对象的Key
(文件名)包括完整路径。
以下是 Keys 的示例:
foo.txt
foo-update.txt
invoices/bar.txt
invoices/bar-update.txt
to-be-updated/grok.txt
最后一行显示了一个名为 的文件夹内的对象to-be-updated
。现实情况是该文件夹实际上并不存在。相反,对象的键(文件名)是to-be-updated/grok.txt
.
因此,如果您的代码删除update
其 Key 中的任何对象,那么它将删除to-be-updated/
文件夹中的所有对象。
另外,请注意文件夹不存在。因此,当从“文件夹”中删除最后一个对象时,该文件夹将不再出现。这没什么好恐慌的。当对象再次放置在该路径中时,它将自动重新出现。
(如果您在 S3 管理控制台中创建了一个文件夹,它实际上会使用该文件夹的名称创建一个长度为零的对象。如果该对象包含单词update
,您的代码将删除该对象,这是删除该文件夹的另一个原因。 )
推荐阅读
- java - 生成哈希 id 作为表中的主键(postgres)
- java - Flyway 使用 Kerberos 身份验证执行 SQL DDL 脚本
- django - PostUpdateView 缺少查询集。定义 PostUpdateView.model、PostUpdateView.queryset,或覆盖 PostUpdateView.get_queryset()
- azure - Azure Flask Web 应用程序 + Azure SQL + Github | 每天500服务器错误
- mysql - 在mysql中的列中拆分日期
- arrays - 如何订购数据验证列表
- windows - Windows 加密 API:下一代 (CNG) 是否受益于 Windows Defender Credential Guard?
- json - 如何将一种形式的 json 模式转换为 cerberus 支持的另一种形式?
- c# - 获取N级嵌套列表视图中项目的索引c#UWP
- java - 如何在不读取整个 InputStream 的情况下使 Wiremock 响应?