我正在使用 PSH 脚本将 csv 文件更新到 Google 共享云端硬盘。上传工作正常。我需要添加删除部分以在上传新版本之前删除文件。当我使用 HTTP 方法 DELETE 时,我得到 正在删除文件:file.csv,ID 为:1xxxxxxxxxxxxxxxxxxxxx-4 无法删除文件 ID 1xxxxxxxxxxxxxxxxxxxx-4。错误:远程服务器返回错误:(404) 未找到。
文件就在那里。该帐户具有完全权限。使用 https://www.googleapis.com/auth/drive
有什么建议吗?我对此很陌生。 :)
使用 PSH 和 Google OAuth 2 上传的文件。删除同一文件时,会出现 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."
}
在您的显示脚本中,
$deleteUri
返回https://www.googleapis.com/drive/v3/files/=true
。我认为这可能是您当前问题的原因。那么,下面的修改怎么样?
$deleteUri = "https://www.googleapis.com/drive/v3/files/$fileId?supportsAllDrives=true"
$deleteUri = "https://www.googleapis.com/drive/v3/files/${fileId}?supportsAllDrives=true"
通过此修改,
$deleteUri
返回https://www.googleapis.com/drive/v3/files/###fileId###?supportsAllDrives=true
。另外,我确认修改后的脚本有效。