Amazon S3: Delete Multiple Objects and Check Each Result
See more S3 - REST Examples
Deletes the explicitly supplied objects. Load qa_data/aws/delete-objects.json with {"objects":[{"key":"documents/old.txt"},{"key":"documents/older.txt","version_id":"VERSION_ID"}]}. Supply 1–1000 unique entries per request. The example does not enumerate a prefix or automatically retry. Requires s3:DeleteObject and, for explicit versions, s3:DeleteObjectVersion.
Without versionId, an unversioned object is permanently removed; a versioned bucket normally creates a delete marker. Explicit data-version deletion is permanent. Retention, legal holds and MFA Delete can restrict deletion. Absent keys can still be acknowledged as deleted. HTTP 200 may contain per-object errors; each returned key/version is matched against the intended batch. Reconcile uncertain or missing results before any retry.
General purpose DeleteObjects uses Content-MD5. The tested AuthAws path omits that header, so this example explicitly constructs Signature Version 4 for the fixed POST /?delete= request and sends it through Rest. This is deliberately not a general URL signer. Do not change the body, hostname, query, or signed headers after signing, or attach AuthAws as a second signer.
For general purpose S3 buckets, using regional HTTPS endpoints and AWS Signature Version 4. Directory buckets (S3 Express), access points, Outposts, and other AWS partitions need their own endpoint/authentication rules. Use a bucket name without dots for these virtual-hosted TLS examples; see the path-style example for dotted names.
Provide current IAM credentials in a private qa_data/aws/s3.json file with string fields access_key, secret_key, and session_token for temporary credentials. Prefer short-lived role credentials. This file is explicitly loaded; these examples do not discover profiles or refresh credentials. Keep it outside public content and source control. The session token is included in the signed request. TLS certificate verification is enabled on the Socket used by Rest.
Transport success and HTTP success are different. Keep full diagnostics private; signed requests and presigned URLs can contain credentials or grant access. For retryable reads use bounded backoff with jitter. Before retrying a write with an uncertain outcome, check the resource state. Keep keys, upload IDs, version IDs, ETags, and large sizes as strings.
Chilkat VBScript Downloads
Dim fso, outFile
Set fso = CreateObject("Scripting.FileSystemObject")
'Create a Unicode (utf-16) output text file.
Set outFile = fso.CreateTextFile("output.txt", True, True)
success = 0
' StringBuilder compares text by value in every generated language.
set textCompare = CreateObject("Chilkat.StringBuilder")
' Assumes Chilkat is unlocked. See Global Unlock Sample.
success = 0
' Private configuration, not a file in public web content or source control.
' Load current IAM credentials authorized for the S3 operation.
set credentials = CreateObject("Chilkat.JsonObject")
credentials.Strict = 1
success = credentials.LoadFile("qa_data/aws/s3.json")
If (success <> 1) Then
outFile.WriteLine("Could not load private AWS credentials.")
WScript.Quit
End If
textCompare.Clear
success = textCompare.SetString(credentials.StringOf("access_key"))
sameText1 = textCompare.ContentsEqual("",1)
If ((credentials.JsonTypeOf("access_key") <> 1) Or (sameText1 = 1)) Then
outFile.WriteLine("Missing or invalid access_key.")
WScript.Quit
End If
textCompare.Clear
success = textCompare.SetString(credentials.StringOf("secret_key"))
sameText2 = textCompare.ContentsEqual("",1)
If ((credentials.JsonTypeOf("secret_key") <> 1) Or (sameText2 = 1)) Then
outFile.WriteLine("Missing or invalid secret_key.")
WScript.Quit
End If
' General purpose bucket in the commercial AWS partition.
region = "us-west-2"
bucketName = "amzn-s3-demo-bucket"
set endpoint = CreateObject("Chilkat.StringBuilder")
success = endpoint.Append(bucketName)
If (success <> 1) Then
outFile.WriteLine("Could not build text.")
WScript.Quit
End If
success = endpoint.Append(".")
If (success <> 1) Then
outFile.WriteLine("Could not build text.")
WScript.Quit
End If
success = endpoint.Append("s3.")
If (success <> 1) Then
outFile.WriteLine("Could not build text.")
WScript.Quit
End If
success = endpoint.Append(region)
If (success <> 1) Then
outFile.WriteLine("Could not build text.")
WScript.Quit
End If
success = endpoint.Append(".amazonaws.com")
If (success <> 1) Then
outFile.WriteLine("Could not build text.")
WScript.Quit
End If
set rest = CreateObject("Chilkat.Rest")
rest.ConnectTimeoutMs = 20000
rest.IdleTimeoutMs = 60000
' Connect to the SAME hostname used for TLS verification and request signing.
set connection = CreateObject("Chilkat.Socket")
connection.RequireSslCertVerify = 1
connection.MaxReadIdleMs = 60000
connection.MaxSendIdleMs = 60000
success = connection.Connect(endpoint.GetAsString(),443,1,20000)
If (success <> 1) Then
outFile.WriteLine("TLS connection failed; inspect diagnostics privately.")
WScript.Quit
End If
success = rest.UseConnection(connection,1)
If (success <> 1) Then
outFile.WriteLine("Could not attach the TLS connection.")
WScript.Quit
End If
set xml = CreateObject("Chilkat.Xml")
xml.Strict = 1
rest.Host = endpoint.GetAsString()
If (credentials.HasMember("session_token") = 1) Then
If (credentials.JsonTypeOf("session_token") <> 1) Then
outFile.WriteLine("session_token must be a string.")
WScript.Quit
End If
End If
' One explicit batch, at most 1000 objects. No prefix expansion or auto-retry.
set batch = CreateObject("Chilkat.JsonObject")
batch.Strict = 1
success = batch.LoadFile("qa_data/aws/delete-objects.json")
If (success <> 1) Then
outFile.WriteLine("Could not load the intended deletion batch.")
WScript.Quit
End If
count = batch.SizeOfArray("objects")
If ((count < 1) Or (count > 1000)) Then
outFile.WriteLine("Supply 1 to 1000 objects in the batch.")
WScript.Quit
End If
xml.Tag = "Delete"
success = xml.AddAttribute("xmlns","http://s3.amazonaws.com/doc/2006-03-01/")
If (success <> 1) Then
outFile.WriteLine("Could not prepare the request.")
WScript.Quit
End If
xml.UpdateChildContent "Quiet","false"
set requested = CreateObject("Chilkat.Hashtable")
set identity = CreateObject("Chilkat.JsonObject")
i = 0
Do While (i < count)
batch.I = i
xml.I = i
textCompare.Clear
success = textCompare.SetString(batch.StringOf("objects[i].key"))
sameText3 = textCompare.ContentsEqual("",1)
If ((batch.JsonTypeOf("objects[i].key") <> 1) Or (sameText3 = 1)) Then
outFile.WriteLine("Each object needs a nonempty key.")
WScript.Quit
End If
key = batch.StringOf("objects[i].key")
version = ""
If (batch.HasMember("objects[i].version_id") = 1) Then
textCompare.Clear
success = textCompare.SetString(batch.StringOf("objects[i].version_id"))
sameText4 = textCompare.ContentsEqual("",1)
If ((batch.JsonTypeOf("objects[i].version_id") <> 1) Or (sameText4 = 1)) Then
outFile.WriteLine("version_id must be a nonempty string when present.")
WScript.Quit
End If
version = batch.StringOf("objects[i].version_id")
xml.UpdateChildContent "Object[i]|VersionId",version
End If
xml.UpdateChildContent "Object[i]|Key",key
success = identity.UpdateString("key",key)
If (success <> 1) Then
outFile.WriteLine("Could not build saved state.")
WScript.Quit
End If
success = identity.UpdateString("version",version)
If (success <> 1) Then
outFile.WriteLine("Could not build saved state.")
WScript.Quit
End If
requestIdentity = identity.Emit()
If (requested.Contains(requestIdentity) = 1) Then
outFile.WriteLine("Duplicate key/version in deletion batch.")
WScript.Quit
End If
success = requested.AddInt(requestIdentity,1)
If (success <> 1) Then
outFile.WriteLine("Could not prepare the request.")
WScript.Quit
End If
i = i + 1
Loop
requestBody = xml.GetXml()
' Explicit signing is used only for this fixed request so Content-MD5 survives.
' Rest sends it; AuthAws must NOT also be configured on this Rest instance.
' Sign this exact POST /?delete= request, including its UTF-8 body and MD5.
' Do not change signed headers, body, endpoint, or query after signing.
set host = CreateObject("Chilkat.StringBuilder")
success = host.Append(endpoint.GetAsString())
set now = CreateObject("Chilkat.CkDateTime")
success = now.SetFromCurrentSystemTime()
If (success <> 1) Then
outFile.WriteLine("Could not read system time.")
WScript.Quit
End If
set timestamp = CreateObject("Chilkat.StringBuilder")
success = timestamp.Append(now.GetAsTimestamp(0))
removedDashes = timestamp.Replace("-","")
removedColons = timestamp.Replace(":","")
amzDate = timestamp.GetAsString()
dateStamp = timestamp.GetRange(0,8,0)
set crypt = CreateObject("Chilkat.Crypt2")
crypt.Charset = "utf-8"
crypt.HashAlgorithm = "md5"
crypt.EncodingMode = "base64"
contentMd5 = crypt.HashStringENC(requestBody)
If (crypt.LastMethodSuccess <> 1) Then
outFile.WriteLine("Could not hash delete body.")
WScript.Quit
End If
crypt.HashAlgorithm = "sha256"
crypt.EncodingMode = "hexlower"
payloadHash = crypt.HashStringENC(requestBody)
If (crypt.LastMethodSuccess <> 1) Then
outFile.WriteLine("Could not hash delete body.")
WScript.Quit
End If
set signedHeaders = CreateObject("Chilkat.StringBuilder")
success = signedHeaders.Append("content-md5;host;x-amz-content-sha256;x-amz-date")
set canonical = CreateObject("Chilkat.StringBuilder")
success = canonical.Append("POST" & vbLf & "/" & vbLf & "delete=" & vbLf & "content-md5:")
success = canonical.Append(contentMd5)
success = canonical.Append(vbLf & "host:")
success = canonical.Append(host.GetAsString())
success = canonical.Append(vbLf & "x-amz-content-sha256:")
success = canonical.Append(payloadHash)
success = canonical.Append(vbLf & "x-amz-date:")
success = canonical.Append(amzDate)
success = canonical.Append(vbLf)
If (credentials.HasMember("session_token") = 1) Then
textCompare.Clear
success = textCompare.SetString(credentials.StringOf("session_token"))
sameText5 = textCompare.ContentsEqual("",1)
If (sameText5 <> 1) Then
success = signedHeaders.Append(";x-amz-security-token")
success = canonical.Append("x-amz-security-token:")
success = canonical.Append(credentials.StringOf("session_token"))
success = canonical.Append(vbLf)
success = rest.AddHeader("x-amz-security-token",credentials.StringOf("session_token"))
If (success <> 1) Then
outFile.WriteLine("Could not prepare the request.")
WScript.Quit
End If
End If
End If
success = canonical.Append(vbLf)
success = canonical.Append(signedHeaders.GetAsString())
success = canonical.Append(vbLf)
success = canonical.Append(payloadHash)
canonicalHash = crypt.HashStringENC(canonical.GetAsString())
If (crypt.LastMethodSuccess <> 1) Then
outFile.WriteLine("Could not hash canonical request.")
WScript.Quit
End If
set scope = CreateObject("Chilkat.StringBuilder")
success = scope.Append(dateStamp)
success = scope.Append("/")
success = scope.Append(region)
success = scope.Append("/s3/aws4_request")
set stringToSign = CreateObject("Chilkat.StringBuilder")
success = stringToSign.Append("AWS4-HMAC-SHA256" & vbLf)
success = stringToSign.Append(amzDate)
success = stringToSign.Append(vbLf)
success = stringToSign.Append(scope.GetAsString())
success = stringToSign.Append(vbLf)
success = stringToSign.Append(canonicalHash)
set initialKey = CreateObject("Chilkat.StringBuilder")
success = initialKey.Append("AWS4")
success = initialKey.Append(credentials.StringOf("secret_key"))
crypt.MacAlgorithm = "hmac"
success = crypt.SetMacKeyString(initialKey.GetAsString())
If (success <> 1) Then
outFile.WriteLine("Could not set signing key.")
WScript.Quit
End If
derivedKey = crypt.MacStringENC(dateStamp)
If (crypt.LastMethodSuccess <> 1) Then
outFile.WriteLine("Could not derive date signing key.")
WScript.Quit
End If
success = crypt.SetMacKeyEncoded(derivedKey,"hex")
If (success <> 1) Then
outFile.WriteLine("Could not set derived signing key.")
WScript.Quit
End If
derivedKey = crypt.MacStringENC(region)
If (crypt.LastMethodSuccess <> 1) Then
outFile.WriteLine("Could not derive signing key.")
WScript.Quit
End If
success = crypt.SetMacKeyEncoded(derivedKey,"hex")
If (success <> 1) Then
outFile.WriteLine("Could not set derived signing key.")
WScript.Quit
End If
derivedKey = crypt.MacStringENC("s3")
If (crypt.LastMethodSuccess <> 1) Then
outFile.WriteLine("Could not derive signing key.")
WScript.Quit
End If
success = crypt.SetMacKeyEncoded(derivedKey,"hex")
If (success <> 1) Then
outFile.WriteLine("Could not set derived signing key.")
WScript.Quit
End If
derivedKey = crypt.MacStringENC("aws4_request")
If (crypt.LastMethodSuccess <> 1) Then
outFile.WriteLine("Could not derive signing key.")
WScript.Quit
End If
success = crypt.SetMacKeyEncoded(derivedKey,"hex")
If (success <> 1) Then
outFile.WriteLine("Could not set final signing key.")
WScript.Quit
End If
signature = crypt.MacStringENC(stringToSign.GetAsString())
If (crypt.LastMethodSuccess <> 1) Then
outFile.WriteLine("Could not sign delete request.")
WScript.Quit
End If
set authorization = CreateObject("Chilkat.StringBuilder")
success = authorization.Append("AWS4-HMAC-SHA256 Credential=")
success = authorization.Append(credentials.StringOf("access_key"))
success = authorization.Append("/")
success = authorization.Append(scope.GetAsString())
success = authorization.Append(", SignedHeaders=")
success = authorization.Append(signedHeaders.GetAsString())
success = authorization.Append(", Signature=")
success = authorization.Append(signature)
success = rest.AddHeader("Authorization",authorization.GetAsString())
If (success <> 1) Then
outFile.WriteLine("Could not prepare the request.")
WScript.Quit
End If
success = rest.AddHeader("Content-MD5",contentMd5)
If (success <> 1) Then
outFile.WriteLine("Could not prepare the request.")
WScript.Quit
End If
success = rest.AddHeader("x-amz-content-sha256",payloadHash)
If (success <> 1) Then
outFile.WriteLine("Could not prepare the request.")
WScript.Quit
End If
success = rest.AddHeader("x-amz-date",amzDate)
If (success <> 1) Then
outFile.WriteLine("Could not prepare the request.")
WScript.Quit
End If
success = rest.AddQueryParam("delete","")
If (success <> 1) Then
outFile.WriteLine("Could not prepare the request.")
WScript.Quit
End If
responseBody = rest.FullRequestString("POST","/",requestBody)
If (rest.LastMethodSuccess <> 1) Then
outFile.WriteLine("Request did not complete; inspect diagnostics privately.")
WScript.Quit
End If
If (rest.ResponseStatusCode <> 200) Then
outFile.WriteLine("S3 HTTP status: " & rest.ResponseStatusCode)
success = xml.LoadXml(responseBody)
textCompare.Clear
success = textCompare.SetString(xml.Tag)
sameText6 = textCompare.ContentsEqual("Error",1)
If ((success = 1) And (sameText6 = 1)) Then
outFile.WriteLine("S3 error code: " & xml.GetChildContent("Code"))
End If
' Keep signed headers, credentials, URLs, and full diagnostics private.
' A timeout may leave a write's outcome uncertain. Check before retrying.
WScript.Quit
End If
success = xml.LoadXml(responseBody)
If (success <> 1) Then
outFile.WriteLine("Expected well-formed XML.")
WScript.Quit
End If
textCompare.Clear
success = textCompare.SetString(xml.Tag)
sameText7 = textCompare.ContentsEqual("DeleteResult",1)
If (sameText7 <> 1) Then
outFile.WriteLine("Unexpected S3 response element; this is not a successful result.")
WScript.Quit
End If
deleted = xml.NumChildrenHavingTag("Deleted")
failed = xml.NumChildrenHavingTag("Error")
If (deleted + failed <> count) Then
outFile.WriteLine("Incomplete result: reconcile every requested object before retrying.")
WScript.Quit
End If
set received = CreateObject("Chilkat.Hashtable")
resultType = 0
Do While (resultType < 2)
itemTag = "Deleted"
resultCount = deleted
If (resultType = 1) Then
itemTag = "Error"
resultCount = failed
End If
j = 0
Do While (j < resultCount)
xml.I = j
set itemPath = CreateObject("Chilkat.StringBuilder")
success = itemPath.Append(itemTag)
If (success <> 1) Then
outFile.WriteLine("Could not build text.")
WScript.Quit
End If
success = itemPath.Append("[i]")
If (success <> 1) Then
outFile.WriteLine("Could not build text.")
WScript.Quit
End If
' item is a Chilkat.Xml
Set item = xml.FindChild(itemPath.GetAsString())
If (xml.LastMethodSuccess <> 1) Then
outFile.WriteLine("Missing deletion result entry.")
WScript.Quit
End If
resultKey = item.GetChildContent("Key")
resultVersion = ""
If (item.HasChildWithTag("VersionId") = 1) Then
resultVersion = item.GetChildContent("VersionId")
End If
success = identity.UpdateString("key",resultKey)
If (success <> 1) Then
outFile.WriteLine("Could not build saved state.")
WScript.Quit
End If
success = identity.UpdateString("version",resultVersion)
If (success <> 1) Then
outFile.WriteLine("Could not build saved state.")
WScript.Quit
End If
responseIdentity = identity.Emit()
If ((requested.Contains(responseIdentity) <> 1) Or (received.Contains(responseIdentity) = 1)) Then
outFile.WriteLine("Unexpected or duplicated deletion result; reconcile manually.")
WScript.Quit
End If
success = received.AddInt(responseIdentity,1)
If (success <> 1) Then
outFile.WriteLine("Could not prepare the request.")
WScript.Quit
End If
outFile.WriteLine(itemTag & ": " & resultKey)
If (resultType = 1) Then
outFile.WriteLine("Error code: " & item.GetChildContent("Code"))
End If
j = j + 1
Loop
resultType = resultType + 1
Loop
If (failed > 0) Then
outFile.WriteLine("Batch has per-object failures. Do not retry successful entries.")
WScript.Quit
End If
outFile.WriteLine("All requested deletions acknowledged.")
outFile.Close