如何用Google Apps Script在同一Drive目录复制指定用户文件并替换
Got it, let's solve this cross-domain ownership headache once and for all. Since Google blocks direct ownership transfers between domains, creating a duplicate in the same folder and swapping out the original is the way to go. Here's a fully functional Google Apps Script implementation tailored to your needs:
1. Script Overview
This script will:
- Recursively traverse your target Google Drive folder (including all subfolders)
- Locate files owned by a specific external user (supports Google Docs, Sheets, and PDFs)
- Create an exact copy of each matching file in the same directory
- Rename the copy to match the original file's name
- Move the original file to the trash (safer than permanent deletion initially)
2. Full Script Code
function replaceCrossDomainFiles() { // --- CONFIGURE THESE VALUES FIRST --- const targetOwnerEmail = 'external-user@other-domain.com'; // Email of the external owner to target const allowedMimeTypes = [ 'application/vnd.google-apps.document', // Google Docs 'application/vnd.google-apps.spreadsheet', // Google Sheets 'application/pdf' // PDF files ]; const rootFolderId = 'your-folder-id-here'; // ID of the root folder to start traversing from // ------------------------------------ // Start processing from the root folder processFolder(DriveApp.getFolderById(rootFolderId), targetOwnerEmail, allowedMimeTypes); } /** * Recursively processes a folder and its subfolders * @param {GoogleAppsScript.Drive.Folder} folder Current folder to process * @param {string} targetOwnerEmail Email of the owner we're targeting * @param {string[]} allowedMimeTypes List of file types to process */ function processFolder(folder, targetOwnerEmail, allowedMimeTypes) { // Process all files in the current folder const files = folder.getFiles(); while (files.hasNext()) { const file = files.next(); const owner = file.getOwner(); // Check if the file matches our criteria if (owner && owner.getEmail() === targetOwnerEmail && allowedMimeTypes.includes(file.getMimeType())) { try { const originalName = file.getName(); const originalId = file.getId(); // Step 1: Create a copy of the file in the same folder const tempCopy = file.makeCopy(`${originalName} - Temp Copy`, folder); // Step 2: Move the original file to trash (reversible if needed) file.setTrashed(true); // Step 3: Rename the copy to match the original file's name tempCopy.setName(originalName); console.log(`Successfully processed: ${originalName} | Original ID: ${originalId} | Copy ID: ${tempCopy.getId()}`); } catch (error) { console.error(`Failed to process ${file.getName()}: ${error.message}`); } } } // Recursively process all subfolders const subFolders = folder.getFolders(); while (subFolders.hasNext()) { processFolder(subFolders.next(), targetOwnerEmail, allowedMimeTypes); } }
3. Setup & Usage Steps
- Create a new Apps Script project: Go to Google Drive, right-click > More > Google Apps Script.
- Paste the code: Replace the default
myFunction()with the code above. - Configure the parameters:
- Update
targetOwnerEmailwith the email of the external user whose files you want to replace. - Replace
rootFolderIdwith the ID of your starting folder (you can get this from the folder's URL:https://drive.google.com/drive/folders/[FOLDER_ID]).
- Update
- Authorize the script: Click the run button (▶️) and select
replaceCrossDomainFiles. You'll need to grant the script permission to access your Google Drive (follow the prompts, you may need to click "Advanced" > "Go to [Project Name]" to proceed). - Monitor progress: Check the execution logs by going to View > Logs to see which files were processed or if any errors occurred.
4. Critical Notes
- Safety first: The script moves original files to the trash instead of permanently deleting them. Double-check the copies before emptying the trash!
- Permissions: Make sure the account running the script has edit/delete access to all target files and folders. If you hit permission errors, you'll need to adjust sharing settings first.
- File types: To add more file types (like Google Slides), just add their MIME type to the
allowedMimeTypesarray (e.g.,'application/vnd.google-apps.presentation'). - Rate limits: If you're processing hundreds of files, add a small delay inside the file loop (e.g.,
Utilities.sleep(1000)to wait 1 second per file) to avoid hitting Google's API rate limits. - Duplicate names: If there's already a file with the same name in the folder (not the original), the rename step will fail. You can adjust the logic to handle this (e.g., append a timestamp to the copy name) if needed.
内容的提问来源于stack exchange,提问作者Ricardo Coto Oviedo
相关产品推荐
相关产品推荐

