Automate Google Drive test data creation with Google Apps Script

Working with Google Workspace Enterprise customers we recommend using a DEV/Test Google Workspace domain. If you purchase your Workspace licences through a Google Partner you should be able to get a free test domain, which admins can use to test features like Data Loss Prevention, Context Aware-Access without fear of breaking things for your live domain.

Unfortunately there are no convenient settings or data duplication so configuring your test environment can be a challenge. To help create some dummy data with a little help from Gemini I was able to create the following  createDummyFoldersWithNesting() function:  

function createDummyFoldersWithNesting() {
  // Get the starting point for the dummy folder structure
  // Replace with your desired folder ID or use 'root' to start in the root of your My Drive
  const rootFolder = DriveApp.getFolderById("YOUR_FOLDER_ID"); 

  // Configuration for the dummy structure
  const maxNestingLevel = 3;        // How many levels deep the structure will go
  const maxFoldersPerLevel = 5;     // Maximum number of folders to create in each level
  const maxFilesPerFolder = 5;      // Maximum number of files to create in each folder
  const fileFolderPrefix = 'Dummy'  // Text added to the start of all folders/files

  // ---------------------------- //

  // Array of file types we want to create (Documents, Sheets, Slides)
  const fileTypes = ["document", "spreadsheet", "presentation"];
  
  // Function to randomly pick a file type from the array
  const randomFileType = () => fileTypes[Math.floor(Math.random() * fileTypes.length)];

  // Recursive function to create nested folders and files
  const createNestedFolders = (parentFolder, currentLevel) => {
    // Decide how many folders to create in this level
    const numFolders = Math.floor(Math.random() * maxFoldersPerLevel) + 1; // Randomly create 1-5 folders
    console.log(`Creating ${numFolders} folders in ${parentFolder.getName()} (level ${currentLevel})`);

    // Create folders and files within them
    for (let i = 0; i < numFolders; i++) {
      const levelName = `${currentLevel}.${i + 1}`;    // Name for the folder (e.g., "1.2" for 2nd folder in level 1)
      const folder = parentFolder.createFolder(`${fileFolderPrefix} Folder ${levelName}`); // Create the new folder

      // Create files within the new folder
      Array.from({ length: maxFilesPerFolder }, (_, index) => {   // Create up to 5 files
        const fileType = randomFileType();                     // Pick a random file type
        const fileMetadata = {                                // Prepare information about the new file
          name: `${fileFolderPrefix} ${fileType[0].toUpperCase() + fileType.slice(1)} ${levelName}.${index + 1}`,  // File name (e.g., "Dummy Document 1.2.3")
          mimeType: `application/vnd.google-apps.${fileType}`, // Google Apps Script file type (document, spreadsheet, or presentation)
          parents: [folder.getId()]                           // Place the file in the newly created folder
        };
        Drive.Files.create(fileMetadata, undefined, { supportsAllDrives: true }); // Create the file in Google Drive
        console.log(`  Created ${fileType} in folder ID: ${folder.getId()}`);
      });

      // Recursive call: If haven't reached max nesting level, create more folders in this one
      if (currentLevel < maxNestingLevel) {
        createNestedFolders(folder, currentLevel + 1);
      }
    }
  };

  // Start the process
  console.log("Starting dummy folder creation...");
  createNestedFolders(rootFolder, 1);
  console.log("Finished creating dummy folders!");
}

To use the script

  1. Copy into the Apps Script Editor
  2. Enable the Google Drive Advanced Service
  3. Configure the settings inside the function for the root folder and the number of files/folders to generate

Gemini suggested I highlighted the following key points:

  • Recursion: The createNestedFolders function calls itself to create folders within folders.
  • Randomness: The script randomly determines the number of folders and files to create, and the types of files.
  • Google Apps Script Services: It uses DriveApp and Drive.Files to interact with Google Drive.
  • File Metadata: When creating files, it uses the mimeType property to specify the Google Apps Script file type.

Whilst Gemini wrote a lot of the code for me (with a little guidance), there were a couple of gotchas I’ll highlight.

Drive.Files.create instead of DriveApp.createFile(name, content, mimeType) – the current documentation would suggest that you can use the .createFile() method and include a MimeType like GOOGLE_SHEETS, but as explained in this Stackoverflow post Google have said “After extensive consideration, we have determined that DriveApp.createFile() should not be used to create MimeType.GOOGLE_* files.” 

I could have asked Gemini to rewrite this to use DocumentApp, SpreadsheetApp or SlidesApp .create() methods e.g. SpreadsheetApp.create() but then I would have to move into a folder, use extra scopes, which all felt a bit messy so instead opted for Drive.Files.create.

Drive.Files.create supporting Shared Drives without a blob – when using Advanced Services there is a bit of cross referencing required between the auto-complete in the script editor and the associated API documentation. For my script I wanted to support creating files in Shared Drive. To do this requires adding the supportsAllDrives as optionalArgs in the Drive.Files.create(resource, mediaData, optionalArgs) method. As I only wanted blank Docs, Sheets and Slides I was scratching my head as to what to include for the mediaData blob. Fortunately this issue was discussed in the Google Apps Script Community – Google Group and it was clear I could use null or undefined. 

chevron_left

Leave a comment

Your email address will not be published. Required fields are marked *

Comment
Name
Email
Website

css.php