将 DeleteObjects 与 Amazon SDK 或命令行工具结合使用 - Amazon Simple Storage Service
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

DeleteObjects 与 Amazon SDK 或命令行工具结合使用

以下代码示例演示如何使用 DeleteObjects

操作示例是大型程序的代码摘录,必须在上下文中运行。在以下代码示例中,您可以查看此操作的上下文:

.NET
Amazon SDK for .NET
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

从 S3 存储桶中删除所有对象。

/// <summary> /// Delete all of the objects stored in an existing Amazon S3 bucket. /// </summary> /// <param name="client">An initialized Amazon S3 client object.</param> /// <param name="bucketName">The name of the bucket from which the /// contents will be deleted.</param> /// <returns>A boolean value that represents the success or failure of /// deleting all of the objects in the bucket.</returns> public static async Task<bool> DeleteBucketContentsAsync(IAmazonS3 client, string bucketName) { // Iterate over the contents of the bucket and delete all objects. var request = new ListObjectsV2Request { BucketName = bucketName, }; try { ListObjectsV2Response response; do { response = await client.ListObjectsV2Async(request); response.S3Objects .ForEach(async obj => await client.DeleteObjectAsync(bucketName, obj.Key)); // If the response is truncated, set the request ContinuationToken // from the NextContinuationToken property of the response. request.ContinuationToken = response.NextContinuationToken; } while (response.IsTruncated); return true; } catch (AmazonS3Exception ex) { Console.WriteLine($"Error deleting objects: {ex.Message}"); return false; } }

删除不受版本控制的 S3 存储桶中的多个对象。

using System; using System.Collections.Generic; using System.Threading.Tasks; using Amazon.S3; using Amazon.S3.Model; /// <summary> /// This example shows how to delete multiple objects from an Amazon Simple /// Storage Service (Amazon S3) bucket. /// </summary> public class DeleteMultipleObjects { /// <summary> /// The Main method initializes the Amazon S3 client and the name of /// the bucket and then passes those values to MultiObjectDeleteAsync. /// </summary> public static async Task Main() { const string bucketName = "doc-example-bucket"; // If the Amazon S3 bucket from which you wish to delete objects is not // located in the same AWS Region as the default user, define the // AWS Region for the Amazon S3 bucket as a parameter to the client // constructor. IAmazonS3 s3Client = new AmazonS3Client(); await MultiObjectDeleteAsync(s3Client, bucketName); } /// <summary> /// This method uses the passed Amazon S3 client to first create and then /// delete three files from the named bucket. /// </summary> /// <param name="client">The initialized Amazon S3 client object used to call /// Amazon S3 methods.</param> /// <param name="bucketName">The name of the Amazon S3 bucket where objects /// will be created and then deleted.</param> public static async Task MultiObjectDeleteAsync(IAmazonS3 client, string bucketName) { // Create three sample objects which we will then delete. var keysAndVersions = await PutObjectsAsync(client, 3, bucketName); // Now perform the multi-object delete, passing the key names and // version IDs. Since we are working with a non-versioned bucket, // the object keys collection includes null version IDs. DeleteObjectsRequest multiObjectDeleteRequest = new DeleteObjectsRequest { BucketName = bucketName, Objects = keysAndVersions, }; // You can add a specific object key to the delete request using the // AddKey method of the multiObjectDeleteRequest. try { DeleteObjectsResponse response = await client.DeleteObjectsAsync(multiObjectDeleteRequest); Console.WriteLine("Successfully deleted all the {0} items", response.DeletedObjects.Count); } catch (DeleteObjectsException e) { PrintDeletionErrorStatus(e); } } /// <summary> /// Prints the list of errors raised by the call to DeleteObjectsAsync. /// </summary> /// <param name="ex">A collection of exceptions returned by the call to /// DeleteObjectsAsync.</param> public static void PrintDeletionErrorStatus(DeleteObjectsException ex) { DeleteObjectsResponse errorResponse = ex.Response; Console.WriteLine("x {0}", errorResponse.DeletedObjects.Count); Console.WriteLine($"Successfully deleted {errorResponse.DeletedObjects.Count}."); Console.WriteLine($"No. of objects failed to delete = {errorResponse.DeleteErrors.Count}"); Console.WriteLine("Printing error data..."); foreach (DeleteError deleteError in errorResponse.DeleteErrors) { Console.WriteLine($"Object Key: {deleteError.Key}\t{deleteError.Code}\t{deleteError.Message}"); } } /// <summary> /// This method creates simple text file objects that can be used in /// the delete method. /// </summary> /// <param name="client">The Amazon S3 client used to call PutObjectAsync.</param> /// <param name="number">The number of objects to create.</param> /// <param name="bucketName">The name of the bucket where the objects /// will be created.</param> /// <returns>A list of keys (object keys) and versions that the calling /// method will use to delete the newly created files.</returns> public static async Task<List<KeyVersion>> PutObjectsAsync(IAmazonS3 client, int number, string bucketName) { List<KeyVersion> keys = new List<KeyVersion>(); for (int i = 0; i < number; i++) { string key = "ExampleObject-" + new System.Random().Next(); PutObjectRequest request = new PutObjectRequest { BucketName = bucketName, Key = key, ContentBody = "This is the content body!", }; PutObjectResponse response = await client.PutObjectAsync(request); // For non-versioned bucket operations, we only need the // object key. KeyVersion keyVersion = new KeyVersion { Key = key, }; keys.Add(keyVersion); } return keys; } }

删除受版本控制的 S3 存储桶中的多个对象。

using System; using System.Collections.Generic; using System.Threading.Tasks; using Amazon.S3; using Amazon.S3.Model; /// <summary> /// This example shows how to delete objects in a version-enabled Amazon /// Simple StorageService (Amazon S3) bucket. /// </summary> public class DeleteMultipleObjects { public static async Task Main() { string bucketName = "doc-example-bucket"; // If the AWS Region for your Amazon S3 bucket is different from // the AWS Region of the default user, define the AWS Region for // the Amazon S3 bucket and pass it to the client constructor // like this: // RegionEndpoint bucketRegion = RegionEndpoint.USWest2; IAmazonS3 s3Client; s3Client = new AmazonS3Client(); await DeleteMultipleObjectsFromVersionedBucketAsync(s3Client, bucketName); } /// <summary> /// This method removes multiple versions and objects from a /// version-enabled Amazon S3 bucket. /// </summary> /// <param name="client">The initialized Amazon S3 client object used to call /// DeleteObjectVersionsAsync, DeleteObjectsAsync, and /// RemoveDeleteMarkersAsync.</param> /// <param name="bucketName">The name of the bucket from which to delete /// objects.</param> public static async Task DeleteMultipleObjectsFromVersionedBucketAsync(IAmazonS3 client, string bucketName) { // Delete objects (specifying object version in the request). await DeleteObjectVersionsAsync(client, bucketName); // Delete objects (without specifying object version in the request). var deletedObjects = await DeleteObjectsAsync(client, bucketName); // Additional exercise - remove the delete markers Amazon S3 returned from // the preceding response. This results in the objects reappearing // in the bucket (you can verify the appearance/disappearance of // objects in the console). await RemoveDeleteMarkersAsync(client, bucketName, deletedObjects); } /// <summary> /// Creates and then deletes non-versioned Amazon S3 objects and then deletes /// them again. The method returns a list of the Amazon S3 objects deleted. /// </summary> /// <param name="client">The initialized Amazon S3 client object used to call /// PubObjectsAsync and NonVersionedDeleteAsync.</param> /// <param name="bucketName">The name of the bucket where the objects /// will be created and then deleted.</param> /// <returns>A list of DeletedObjects.</returns> public static async Task<List<DeletedObject>> DeleteObjectsAsync(IAmazonS3 client, string bucketName) { // Upload the sample objects. var keysAndVersions2 = await PutObjectsAsync(client, bucketName, 3); // Delete objects using only keys. Amazon S3 creates a delete marker and // returns its version ID in the response. List<DeletedObject> deletedObjects = await NonVersionedDeleteAsync(client, bucketName, keysAndVersions2); return deletedObjects; } /// <summary> /// This method creates several temporary objects and then deletes them. /// </summary> /// <param name="client">The S3 client.</param> /// <param name="bucketName">Name of the bucket.</param> /// <returns>Async task.</returns> public static async Task DeleteObjectVersionsAsync(IAmazonS3 client, string bucketName) { // Upload the sample objects. var keysAndVersions1 = await PutObjectsAsync(client, bucketName, 3); // Delete the specific object versions. await VersionedDeleteAsync(client, bucketName, keysAndVersions1); } /// <summary> /// Displays the list of information about deleted files to the console. /// </summary> /// <param name="e">Error information from the delete process.</param> private static void DisplayDeletionErrors(DeleteObjectsException e) { var errorResponse = e.Response; Console.WriteLine($"No. of objects successfully deleted = {errorResponse.DeletedObjects.Count}"); Console.WriteLine($"No. of objects failed to delete = {errorResponse.DeleteErrors.Count}"); Console.WriteLine("Printing error data..."); foreach (var deleteError in errorResponse.DeleteErrors) { Console.WriteLine($"Object Key: {deleteError.Key}\t{deleteError.Code}\t{deleteError.Message}"); } } /// <summary> /// Delete multiple objects from a version-enabled bucket. /// </summary> /// <param name="client">The initialized Amazon S3 client object used to call /// DeleteObjectVersionsAsync, DeleteObjectsAsync, and /// RemoveDeleteMarkersAsync.</param> /// <param name="bucketName">The name of the bucket from which to delete /// objects.</param> /// <param name="keys">A list of key names for the objects to delete.</param> private static async Task VersionedDeleteAsync(IAmazonS3 client, string bucketName, List<KeyVersion> keys) { var multiObjectDeleteRequest = new DeleteObjectsRequest { BucketName = bucketName, Objects = keys, // This includes the object keys and specific version IDs. }; try { Console.WriteLine("Executing VersionedDelete..."); DeleteObjectsResponse response = await client.DeleteObjectsAsync(multiObjectDeleteRequest); Console.WriteLine($"Successfully deleted all the {response.DeletedObjects.Count} items"); } catch (DeleteObjectsException ex) { DisplayDeletionErrors(ex); } } /// <summary> /// Deletes multiple objects from a non-versioned Amazon S3 bucket. /// </summary> /// <param name="client">The initialized Amazon S3 client object used to call /// DeleteObjectVersionsAsync, DeleteObjectsAsync, and /// RemoveDeleteMarkersAsync.</param> /// <param name="bucketName">The name of the bucket from which to delete /// objects.</param> /// <param name="keys">A list of key names for the objects to delete.</param> /// <returns>A list of the deleted objects.</returns> private static async Task<List<DeletedObject>> NonVersionedDeleteAsync(IAmazonS3 client, string bucketName, List<KeyVersion> keys) { // Create a request that includes only the object key names. DeleteObjectsRequest multiObjectDeleteRequest = new DeleteObjectsRequest(); multiObjectDeleteRequest.BucketName = bucketName; foreach (var key in keys) { multiObjectDeleteRequest.AddKey(key.Key); } // Execute DeleteObjectsAsync. // The DeleteObjectsAsync method adds a delete marker for each // object deleted. You can verify that the objects were removed // using the Amazon S3 console. DeleteObjectsResponse response; try { Console.WriteLine("Executing NonVersionedDelete..."); response = await client.DeleteObjectsAsync(multiObjectDeleteRequest); Console.WriteLine("Successfully deleted all the {0} items", response.DeletedObjects.Count); } catch (DeleteObjectsException ex) { DisplayDeletionErrors(ex); throw; // Some deletions failed. Investigate before continuing. } // This response contains the DeletedObjects list which we use to delete the delete markers. return response.DeletedObjects; } /// <summary> /// Deletes the markers left after deleting the temporary objects. /// </summary> /// <param name="client">The initialized Amazon S3 client object used to call /// DeleteObjectVersionsAsync, DeleteObjectsAsync, and /// RemoveDeleteMarkersAsync.</param> /// <param name="bucketName">The name of the bucket from which to delete /// objects.</param> /// <param name="deletedObjects">A list of the objects that were deleted.</param> private static async Task RemoveDeleteMarkersAsync(IAmazonS3 client, string bucketName, List<DeletedObject> deletedObjects) { var keyVersionList = new List<KeyVersion>(); foreach (var deletedObject in deletedObjects) { KeyVersion keyVersion = new KeyVersion { Key = deletedObject.Key, VersionId = deletedObject.DeleteMarkerVersionId, }; keyVersionList.Add(keyVersion); } // Create another request to delete the delete markers. var multiObjectDeleteRequest = new DeleteObjectsRequest { BucketName = bucketName, Objects = keyVersionList, }; // Now, delete the delete marker to bring your objects back to the bucket. try { Console.WriteLine("Removing the delete markers ....."); var deleteObjectResponse = await client.DeleteObjectsAsync(multiObjectDeleteRequest); Console.WriteLine($"Successfully deleted the {deleteObjectResponse.DeletedObjects.Count} delete markers"); } catch (DeleteObjectsException ex) { DisplayDeletionErrors(ex); } } /// <summary> /// Create temporary Amazon S3 objects to show how object deletion wors in an /// Amazon S3 bucket with versioning enabled. /// </summary> /// <param name="client">The initialized Amazon S3 client object used to call /// PutObjectAsync to create temporary objects for the example.</param> /// <param name="bucketName">A string representing the name of the S3 /// bucket where we will create the temporary objects.</param> /// <param name="number">The number of temporary objects to create.</param> /// <returns>A list of the KeyVersion objects.</returns> private static async Task<List<KeyVersion>> PutObjectsAsync(IAmazonS3 client, string bucketName, int number) { var keys = new List<KeyVersion>(); for (var i = 0; i < number; i++) { string key = "ObjectToDelete-" + new System.Random().Next(); PutObjectRequest request = new PutObjectRequest { BucketName = bucketName, Key = key, ContentBody = "This is the content body!", }; var response = await client.PutObjectAsync(request); KeyVersion keyVersion = new KeyVersion { Key = key, VersionId = response.VersionId, }; keys.Add(keyVersion); } return keys; } }
  • 有关 API 详细信息,请参阅 Amazon SDK for .NET API 参考中的 DeleteObjects

Bash
Amazon CLI 及 Bash 脚本
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

############################################################################### # function errecho # # This function outputs everything sent to it to STDERR (standard error output). ############################################################################### function errecho() { printf "%s\n" "$*" 1>&2 } ############################################################################### # function delete_items_in_bucket # # This function deletes the specified list of keys from the specified bucket. # # Parameters: # $1 - The name of the bucket. # $2 - A list of keys in the bucket to delete. # Returns: # 0 - If successful. # 1 - If it fails. ############################################################################### function delete_items_in_bucket() { local bucket_name=$1 local keys=$2 local response # Create the JSON for the items to delete. local delete_items delete_items="{\"Objects\":[" for key in $keys; do delete_items="$delete_items{\"Key\": \"$key\"}," done delete_items=${delete_items%?} # Remove the final comma. delete_items="$delete_items]}" response=$(aws s3api delete-objects \ --bucket "$bucket_name" \ --delete "$delete_items") # shellcheck disable=SC2181 if [[ $? -ne 0 ]]; then errecho "ERROR: AWS reports s3api delete-object operation failed.\n$response" return 1 fi }
  • 有关 API 详细信息,请参阅《Amazon CLI 命令参考》中的 DeleteObjects

C++
适用于 C++ 的 SDK
注意

查看 GitHub,了解更多信息。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

bool AwsDoc::S3::DeleteObjects(const std::vector<Aws::String> &objectKeys, const Aws::String &fromBucket, const Aws::Client::ClientConfiguration &clientConfig) { Aws::S3::S3Client client(clientConfig); Aws::S3::Model::DeleteObjectsRequest request; Aws::S3::Model::Delete deleteObject; for (const Aws::String& objectKey : objectKeys) { deleteObject.AddObjects(Aws::S3::Model::ObjectIdentifier().WithKey(objectKey)); } request.SetDelete(deleteObject); request.SetBucket(fromBucket); Aws::S3::Model::DeleteObjectsOutcome outcome = client.DeleteObjects(request); if (!outcome.IsSuccess()) { auto err = outcome.GetError(); std::cerr << "Error deleting objects. " << err.GetExceptionName() << ": " << err.GetMessage() << std::endl; } else { std::cout << "Successfully deleted the objects."; for (size_t i = 0; i < objectKeys.size(); ++i) { std::cout << objectKeys[i]; if (i < objectKeys.size() - 1) { std::cout << ", "; } } std::cout << " from bucket " << fromBucket << "." << std::endl; } return outcome.IsSuccess(); }
  • 有关 API 详细信息,请参阅 Amazon SDK for C++ API 参考中的 DeleteObjects

CLI
Amazon CLI

以下命令从名为 my-bucket 的存储桶中删除对象:

aws s3api delete-objects --bucket my-bucket --delete file://delete.json

delete.json 是当前目录中指定要删除的对象的 JSON 文档:

{ "Objects": [ { "Key": "test1.txt" } ], "Quiet": false }

输出:

{ "Deleted": [ { "DeleteMarkerVersionId": "mYAT5Mc6F7aeUL8SS7FAAqUPO1koHwzU", "Key": "test1.txt", "DeleteMarker": true } ] }
  • 有关 API 详细信息,请参阅《Amazon CLI 命令参考》中的 DeleteObjects

Go
适用于 Go V2 的 SDK
注意

查看 GitHub,了解更多信息。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

// BucketBasics encapsulates the Amazon Simple Storage Service (Amazon S3) actions // used in the examples. // It contains S3Client, an Amazon S3 service client that is used to perform bucket // and object actions. type BucketBasics struct { S3Client *s3.Client } // DeleteObjects deletes a list of objects from a bucket. func (basics BucketBasics) DeleteObjects(bucketName string, objectKeys []string) error { var objectIds []types.ObjectIdentifier for _, key := range objectKeys { objectIds = append(objectIds, types.ObjectIdentifier{Key: aws.String(key)}) } output, err := basics.S3Client.DeleteObjects(context.TODO(), &s3.DeleteObjectsInput{ Bucket: aws.String(bucketName), Delete: &types.Delete{Objects: objectIds}, }) if err != nil { log.Printf("Couldn't delete objects from bucket %v. Here's why: %v\n", bucketName, err) } else { log.Printf("Deleted %v objects.\n", len(output.Deleted)) } return err }
  • 有关 API 详细信息,请参阅 Amazon SDK for Go API 参考中的 DeleteObjects

Java
SDK for Java 2.x
注意

查看 GitHub,了解更多信息。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.PutObjectRequest; import software.amazon.awssdk.services.s3.model.ObjectIdentifier; import software.amazon.awssdk.services.s3.model.Delete; import software.amazon.awssdk.services.s3.model.DeleteObjectsRequest; import software.amazon.awssdk.services.s3.model.S3Exception; import java.util.ArrayList; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class DeleteMultiObjects { public static void main(String[] args) { final String usage = """ Usage: <bucketName> Where: bucketName - the Amazon S3 bucket name. """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String bucketName = args[0]; Region region = Region.US_EAST_1; S3Client s3 = S3Client.builder() .region(region) .build(); deleteBucketObjects(s3, bucketName); s3.close(); } public static void deleteBucketObjects(S3Client s3, String bucketName) { // Upload three sample objects to the specfied Amazon S3 bucket. ArrayList<ObjectIdentifier> keys = new ArrayList<>(); PutObjectRequest putOb; ObjectIdentifier objectId; for (int i = 0; i < 3; i++) { String keyName = "delete object example " + i; objectId = ObjectIdentifier.builder() .key(keyName) .build(); putOb = PutObjectRequest.builder() .bucket(bucketName) .key(keyName) .build(); s3.putObject(putOb, RequestBody.fromString(keyName)); keys.add(objectId); } System.out.println(keys.size() + " objects successfully created."); // Delete multiple objects in one request. Delete del = Delete.builder() .objects(keys) .build(); try { DeleteObjectsRequest multiObjectDeleteRequest = DeleteObjectsRequest.builder() .bucket(bucketName) .delete(del) .build(); s3.deleteObjects(multiObjectDeleteRequest); System.out.println("Multiple objects are deleted!"); } catch (S3Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
  • 有关 API 详细信息,请参阅 Amazon SDK for Java 2.x API 参考中的 DeleteObjects

JavaScript
SDK for JavaScript (v3)
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

删除多个对象。

import { DeleteObjectsCommand, S3Client } from "@aws-sdk/client-s3"; const client = new S3Client({}); export const main = async () => { const command = new DeleteObjectsCommand({ Bucket: "test-bucket", Delete: { Objects: [{ Key: "object1.txt" }, { Key: "object2.txt" }], }, }); try { const { Deleted } = await client.send(command); console.log( `Successfully deleted ${Deleted.length} objects from S3 bucket. Deleted objects:`, ); console.log(Deleted.map((d) => ` • ${d.Key}`).join("\n")); } catch (err) { console.error(err); } };
  • 有关 API 详细信息,请参阅 Amazon SDK for JavaScript API 参考中的 DeleteObjects

Kotlin
适用于 Kotlin 的 SDK
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

suspend fun deleteBucketObjects(bucketName: String, objectName: String) { val objectId = ObjectIdentifier { key = objectName } val delOb = Delete { objects = listOf(objectId) } val request = DeleteObjectsRequest { bucket = bucketName delete = delOb } S3Client { region = "us-east-1" }.use { s3 -> s3.deleteObjects(request) println("$objectName was deleted from $bucketName") } }
  • 有关 API 详细信息,请参阅《Amazon SDK for Kotlin API 参考》中的 DeleteObjects

PHP
适用于 PHP 的 SDK
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

从键列表中删除一组对象。

$s3client = new Aws\S3\S3Client(['region' => 'us-west-2']); try { $objects = []; foreach ($contents['Contents'] as $content) { $objects[] = [ 'Key' => $content['Key'], ]; } $this->s3client->deleteObjects([ 'Bucket' => $this->bucketName, 'Delete' => [ 'Objects' => $objects, ], ]); $check = $this->s3client->listObjectsV2([ 'Bucket' => $this->bucketName, ]); if (count($check) <= 0) { throw new Exception("Bucket wasn't empty."); } echo "Deleted all objects and folders from $this->bucketName.\n"; } catch (Exception $exception) { echo "Failed to delete $fileName from $this->bucketName with error: " . $exception->getMessage(); exit("Please fix error with object deletion before continuing."); }
  • 有关 API 的详细信息,请参阅 Amazon SDK for PHP API 参考中的 DeleteObjects

PowerShell
适用于 PowerShell 的工具

示例 1:此命令从存储桶“test-files”中移除对象“sample.txt”。在命令执行之前,系统会提示您进行确认;要取消提示,请使用 -Force 开关。

Remove-S3Object -BucketName test-files -Key sample.txt

示例 2:假设存储桶已配置为启用对象版本,则此命令会从存储桶“test-files”中移除对象“sample.txt”的指定版本。

Remove-S3Object -BucketName test-files -Key sample.txt -VersionId HLbxnx6V9omT6AQYVpks8mmFKQcejpqt

示例 3:此命令通过单个批量操作,从存储桶“test-files”中移除对象“sample1.txt”、“sample2.txt”和“sample3.txt”。无论删除的成功或错误状态如何,服务响应都将列出所有已处理的键。要仅获取服务无法处理的键的错误,请添加 -ReportErrorsOnly 参数(也可以使用别名 -Quiet 来指定此参数)。

Remove-S3Object -BucketName test-files -KeyCollection @( "sample1.txt", "sample2.txt", "sample3.txt" )

示例 4:此示例使用带有 -KeyCollection 参数的内联表达式来获取要删除的对象的键。Get-S3Object 返回 Amazon.S3.Model.S3Object 实例的集合,每个实例都有一个标识对象的字符串类型的 Key(键)成员。

Remove-S3Object -bucketname "test-files" -KeyCollection (Get-S3Object "test-files" -KeyPrefix "prefix/subprefix" | select -ExpandProperty Key)

示例 5:此示例获取存储桶中所有具有键前缀“prefix/subprefix”的对象并将其删除。请注意,一次只能处理一个传入的对象。对于大型集合,可以考虑将集合传递给 cmdlet 的 -InputObject(别名 -S3ObjectCollection)参数,这样,只需调用一次服务即可批量删除。

Get-S3Object -BucketName "test-files" -KeyPrefix "prefix/subprefix" | Remove-S3Object -Force

示例 6:此示例将代表删除标记的 Amazon.S3.Model.S3ObjectVersion 实例的集合传送到 cmdlet 进行删除。请注意,一次只能处理一个传入的对象。对于大型集合,可以考虑将集合传递给 cmdlet 的 -InputObject(别名 -S3ObjectCollection)参数,这样,只需调用一次服务即可批量删除。

(Get-S3Version -BucketName "test-files").Versions | Where {$_.IsDeleteMarker -eq "True"} | Remove-S3Object -Force

示例 7:此脚本显示如何通过构造与 -KeyAndVersionCollection 参数一起使用的对象数组,来批量删除一组对象(在本例中为删除标记)。

$keyVersions = @() $markers = (Get-S3Version -BucketName $BucketName).Versions | Where {$_.IsDeleteMarker -eq "True"} foreach ($marker in $markers) { $keyVersions += @{ Key = $marker.Key; VersionId = $marker.VersionId } } Remove-S3Object -BucketName $BucketName -KeyAndVersionCollection $keyVersions -Force
  • 有关 API 详细信息,请参阅《Amazon Tools for PowerShell Cmdlet 参考》中的 DeleteObjects

Python
SDK for Python(Boto3)
注意

查看 GitHub,了解更多信息。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

使用对象键列表删除一组对象。

class ObjectWrapper: """Encapsulates S3 object actions.""" def __init__(self, s3_object): """ :param s3_object: A Boto3 Object resource. This is a high-level resource in Boto3 that wraps object actions in a class-like structure. """ self.object = s3_object self.key = self.object.key @staticmethod def delete_objects(bucket, object_keys): """ Removes a list of objects from a bucket. This operation is done as a batch in a single request. :param bucket: The bucket that contains the objects. This is a Boto3 Bucket resource. :param object_keys: The list of keys that identify the objects to remove. :return: The response that contains data about which objects were deleted and any that could not be deleted. """ try: response = bucket.delete_objects( Delete={"Objects": [{"Key": key} for key in object_keys]} ) if "Deleted" in response: logger.info( "Deleted objects '%s' from bucket '%s'.", [del_obj["Key"] for del_obj in response["Deleted"]], bucket.name, ) if "Errors" in response: logger.warning( "Could not delete objects '%s' from bucket '%s'.", [ f"{del_obj['Key']}: {del_obj['Code']}" for del_obj in response["Errors"] ], bucket.name, ) except ClientError: logger.exception("Couldn't delete any objects from bucket %s.", bucket.name) raise else: return response

删除桶中的所有对象。

class ObjectWrapper: """Encapsulates S3 object actions.""" def __init__(self, s3_object): """ :param s3_object: A Boto3 Object resource. This is a high-level resource in Boto3 that wraps object actions in a class-like structure. """ self.object = s3_object self.key = self.object.key @staticmethod def empty_bucket(bucket): """ Remove all objects from a bucket. :param bucket: The bucket to empty. This is a Boto3 Bucket resource. """ try: bucket.objects.delete() logger.info("Emptied bucket '%s'.", bucket.name) except ClientError: logger.exception("Couldn't empty bucket '%s'.", bucket.name) raise

通过删除版本控制对象的所有版本永久删除该对象。

def permanently_delete_object(bucket, object_key): """ Permanently deletes a versioned object by deleting all of its versions. Usage is shown in the usage_demo_single_object function at the end of this module. :param bucket: The bucket that contains the object. :param object_key: The object to delete. """ try: bucket.object_versions.filter(Prefix=object_key).delete() logger.info("Permanently deleted all versions of object %s.", object_key) except ClientError: logger.exception("Couldn't delete all versions of %s.", object_key) raise
  • 有关 API 详细信息,请参阅《Amazon SDK for Python (Boto3) API 参考>中的 DeleteObjects

Ruby
适用于 Ruby 的 SDK
注意

查看 GitHub,了解更多信息。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

# Deletes the objects in an Amazon S3 bucket and deletes the bucket. # # @param bucket [Aws::S3::Bucket] The bucket to empty and delete. def delete_bucket(bucket) puts("\nDo you want to delete all of the objects as well as the bucket (y/n)? ") answer = gets.chomp.downcase if answer == "y" bucket.objects.batch_delete! bucket.delete puts("Emptied and deleted bucket #{bucket.name}.\n") end rescue Aws::Errors::ServiceError => e puts("Couldn't empty and delete bucket #{bucket.name}.") puts("\t#{e.code}: #{e.message}") raise end
  • 有关 API 详细信息,请参阅 Amazon SDK for Ruby API 参考中的 DeleteObjects

Rust
适用于 Rust 的 SDK
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

pub async fn delete_objects(client: &Client, bucket_name: &str) -> Result<Vec<String>, Error> { let objects = client.list_objects_v2().bucket(bucket_name).send().await?; let mut delete_objects: Vec<ObjectIdentifier> = vec![]; for obj in objects.contents() { let obj_id = ObjectIdentifier::builder() .set_key(Some(obj.key().unwrap().to_string())) .build() .map_err(Error::from)?; delete_objects.push(obj_id); } let return_keys = delete_objects.iter().map(|o| o.key.clone()).collect(); if !delete_objects.is_empty() { client .delete_objects() .bucket(bucket_name) .delete( Delete::builder() .set_objects(Some(delete_objects)) .build() .map_err(Error::from)?, ) .send() .await?; } let objects: ListObjectsV2Output = client.list_objects_v2().bucket(bucket_name).send().await?; eprintln!("{objects:?}"); match objects.key_count { Some(0) => Ok(return_keys), _ => Err(Error::unhandled( "There were still objects left in the bucket.", )), } }
  • 有关 API 详细信息,请参阅《Amazon SDK for Rust API 参考》中的 DeleteObjects

Swift
SDK for Swift
注意

这是预览版 SDK 的预发布文档。本文档随时可能更改。

注意

查看 GitHub,了解更多信息。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

public func deleteObjects(bucket: String, keys: [String]) async throws { let input = DeleteObjectsInput( bucket: bucket, delete: S3ClientTypes.Delete( objects: keys.map({ S3ClientTypes.ObjectIdentifier(key: $0) }), quiet: true ) ) do { let output = try await client.deleteObjects(input: input) // As of the last update to this example, any errors are returned // in the `output` object's `errors` property. If there are any // errors in this array, throw an exception. Once the error // handling is finalized in later updates to the AWS SDK for // Swift, this example will be updated to handle errors better. guard let errors = output.errors else { return // No errors. } if errors.count != 0 { throw ServiceHandlerError.deleteObjectsError } } catch { throw error } }
  • 有关 API 详细信息,请参阅《Amazon SDK for Swift API 参考》中的 DeleteObjects

有关 Amazon SDK 开发人员指南和代码示例的完整列表,请参阅 将此服务与 Amazon SDK 结合使用。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。