I am using a PSH script to update a csv file to a Google Shared drive. The upload works fine. I need to add a delete section to delete the file before uploading a new version. When I used HTTP Method DELETE I get Deleting file: file.csv with ID: 1xxxxxxxxxxxxxxxxxxxxx-4 Failed to delete file ID 1xxxxxxxxxxxxxxxxxxxx-4. Error: The remote server returned an error: (404) Not Found.
The file is there. The account has full perms. Using https://www.googleapis.com/auth/drive
Any suggestions? I am new at this. :)
File uploaded using PSH and Google OAuth 2. When deleting the same file, it gives 404 Not Found.
# Set the Google Auth parameters
$params = @{
Uri = 'https://accounts.google.com/o/oauth2/token'
Body = @{
refresh_token = $RefreshToken
client_id = $ClientID
client_secret = $ClientSecret
grant_type = 'refresh_token'
}
Method = 'Post'
ContentType = 'application/x-www-form-urlencoded'
}
# Get the access token
$accessToken = (Invoke-RestMethod @params).access_token
# Specify the shared drive ID and file name
$teamDriveId = "xxxxxxxxxxxxxxxPVA"
$fileName = "file.csv"
# Step 1: Search for specific file name within the shared drive without specifying parents
$searchUri = "https://www.googleapis.com/drive/v3/files?q=name='$fileName' and trashed=false&corpora=drive&driveId=$teamDriveId&supportsAllDrives=true&includeItemsFromAllDrives=true"
$searchHeaders = @{
"Authorization" = "Bearer $accessToken"
}
$searchResult = Invoke-RestMethod -Uri $searchUri -Method Get -Headers $searchHeaders
Write-Host "Search response: $($searchResult | ConvertTo-Json)"
# Step 2: Delete files if found
if ($searchResult.files) {
foreach ($file in $searchResult.files) {
$fileId = $file.id
Write-Host "Deleting file: $fileName with ID: $fileId"
$deleteUri = "https://www.googleapis.com/drive/v3/files/$fileId?supportsAllDrives=true"
try {
Invoke-RestMethod -Uri $deleteUri -Method Delete -Headers $searchHeaders
Write-Host "Deleted file ID $fileId successfully."
}
catch {
Write-Host "Failed to delete file ID $fileId. Error: $_"
}
}
} else {
Write-Host "No instances of $fileName found in the shared drive."
}
In your showing script, $deleteUri
returns https://www.googleapis.com/drive/v3/files/=true
. I thought that this might be the reason for your current issue. So, how about the following modification?
$deleteUri = "https://www.googleapis.com/drive/v3/files/$fileId?supportsAllDrives=true"
$deleteUri = "https://www.googleapis.com/drive/v3/files/${fileId}?supportsAllDrives=true"
By this modification, $deleteUri
returns https://www.googleapis.com/drive/v3/files/###fileId###?supportsAllDrives=true
. Also, I confirmed that the modified script worked.