首页 > 解决方案 > 根据文件名删除 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

如果我添加-WhatifRemove-S3Object我得到以下回报:

What if: Performing the operation "Remove-S3Object (DeleteObjects)" on target "".

但是,没有-Whatifpowershell 脚本会提示我Are you sure you want to perform this action? Performing the operation "Remove-S3Object (DeleteObjects)" on target "".4 次,并将删除所有文件和文件夹。

谁能指出我做错了什么?

标签: amazon-web-servicespowershellamazon-s3

解决方案


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,您的代码将删除该对象,这是删除该文件夹的另一个原因。 )


推荐阅读