If you open Google Drive and immediately feel overwhelmed by a chaotic list of loose files sitting in your root directory, you are not alone. It’s the digital equivalent of a messy desk piled high with papers.
Keeping your Drive organised manually is tedious and time-consuming. Fortunately, as experts in Google Workspace automation, we know there is a better way.
Using Google Apps Script, we can create a robust, automated “digital housekeeper” that regularly sweeps your root folder and moves loose files to a designated archive folder.
In this tutorial, we will provide you with a professional-grade script designed for reliability. Unlike basic scripts you might find online, this version includes advanced error handling, detailed logging with stack traces, and precise execution timing.
Let’s reclaim your digital space.
Before copy-pasting the code, you need one thing: a Target Folder. This is where all your loose files will be moved.
Create a new folder in Google Drive (e.g., “Root Archive” or “Inbox”).
Open that folder.
Look at the URL in your browser address bar. It will look like this: drive.google.com/drive/u/0/folders/1EgiJzEcl6H23Rs7rULBdekjUS3VZokUH
Copy the long string of alphanumeric characters at the end. This is your Folder ID. You will need it for the script.
The following script uses the standard DriveApp service. It is optimized for robustness.
Why this script is better than basic examples:
It won’t crash on a single bad file: If one file is locked or corrupted, the script logs the error and moves to the next file instead of stopping entirely.
Stack Traces: It captures detailed error information for easier debugging.
Human-Readable Timing: It tells you exactly how many minutes and seconds the operation took.
Open your Google Apps Script editor (script.new) and paste this code.
IMPORTANT: Update line 4 with your specific Folder ID from the prerequisite step.
/**
* Scans the Root Drive folder and moves loose files to a target archive folder.
* Includes robust error handling and execution timing.
*/
function moveFilesToFolder() {
// =================Configuration=================
// REPLACE WITH YOUR TARGET FOLDER ID
const TARGET_FOLDER_ID = 'YOUR_TARGET_FOLDER_ID_HERE';
// ===============================================
// Capturing start time for custom formatting later
const startTime = new Date();
console.log(`[START] Script started at: ${startTime.toLocaleTimeString()}`);
let successCount = 0;
let errorCount = 0;
try {
// 1. Setup Folders
const sourceFolder = DriveApp.getRootFolder();
// Validate Target Folder exists before starting loop
let targetFolder;
try {
targetFolder = DriveApp.getFolderById(TARGET_FOLDER_ID);
} catch (e) {
throw new Error(`Target folder found. Please check your ID: ${TARGET_FOLDER_ID}\nStack: ${e.stack}`);
}
console.log('Scanning root folder for files...');
// 2. Get Files (DriveApp.getFiles() automatically excludes subfolders)
// This is much more efficient than manually checking MimeTypes.
const files = sourceFolder.getFiles();
while (files.hasNext()) {
const file = files.next();
// Safety Check: Skip the target folder itself if it resides in the source
if (file.getId() === TARGET_FOLDER_ID) continue;
// 3. Granular Try-Catch for individual files
// We wrap the move operation here so one bad file doesn't crash the entire loop.
try {
file.moveTo(targetFolder);
console.log(`Moved: "${file.getName()}"`);
successCount++;
} catch (innerError) {
errorCount++;
// Log detailed info including stack trace for debugging specific files
console.error(
`FAILED to move file: "${file.getName()}" (ID: ${file.getId()})\n` +
`Error Message: ${innerError.message}\n` +
`Stack Trace: ${innerError.stack}`
);
}
}
} catch (criticalError) {
// 4. Global Error Handling (e.g., Drive API is down, total permissions failure)
console.error(
`CRITICAL SCRIPT FAILURE\n` +
`Message: ${criticalError.message}\n` +
`Stack Trace: ${criticalError.stack}`
);
} finally {
// 5. Final Timing Calculation (Minutes and Seconds)
const endTime = new Date();
const timeDiff = endTime - startTime; // difference in milliseconds
const totalSeconds = Math.floor(timeDiff / 1000);
const minutes = Math.floor(totalSeconds / 60);
const seconds = totalSeconds % 60;
console.log('--- EXECUTION SUMMARY ---');
console.log(`Successful Moves: ${successCount}`);
console.log(`Errors Encountered: ${errorCount}`);
console.log(`Total Execution Time: ${minutes}m ${seconds}s`);
console.log('[END] Script finished.');
}
}
A script you have to run manually doesn’t truly solve the problem. To ensure your root folder stays clean forever, we need to set up a Time-Driven Trigger.
Add the following code below the main script in your editor.
Expert Tip: The functions below are designed to delete existing triggers for the main function before creating a new one. This prevents accidental “trigger pile-up,” where the script runs multiple times unnecessarily.
/**
* Run this function ONCE manually to set up a Daily trigger.
* It clears previous triggers to prevent duplicates.
*/
function setupDailyTrigger() {
const functionName = 'moveFilesToFolder';
console.log(`Setting up daily trigger for: ${functionName}...`);
// 1. Clean up old triggers first
deleteAllTriggers(functionName);
// 2. Create the new Daily Trigger
// Runs every day between 1 AM and 2 AM (timezone of the script)
ScriptApp.newTrigger(functionName)
.timeBased()
.everyDays(1)
.atHour(1)
.create();
console.log(`[SUCCESS] Daily trigger set. Your Drive will be cleaned between 1 AM and 2 AM.`);
}
/**
* Utility function to safely delete existing triggers for a specific function.
*/
function deleteAllTriggers(functionName) {
const triggers = ScriptApp.getProjectTriggers();
let deletedCount = 0;
for (let i = 0; i < triggers.length; i++) {
if (triggers[i].getHandlerFunction() === functionName) {
ScriptApp.deleteTrigger(triggers[i]);
deletedCount++;
}
}
if (deletedCount > 0) {
console.log(`[INFO] Removed ${deletedCount} existing trigger(s) to avoid conflicts.`);
}
}
Save your script.
In the editor toolbar, select setupDailyTrigger from the function dropdown menu.
Click the Run button.
Google will ask you to authorise the script to run automatically. Grant permission.
That’s it. Your script will now run every night, ensuring you wake up to a clean Google Drive root folder every morning.
By utilising advanced Google Apps Script techniques like granular error handling and stack trace logging, you haven’t just cleaned a folder; you’ve implemented a reliable, professional automation workflow.
This approach ensures that your digital workspace remains organised without requiring constant manual intervention, freeing up your time for more important tasks.