Organiza tus páginas con colecciones Guarda y categoriza el contenido según tus preferencias.
El servicio avanzado de Drive te permite usar la API de Google Drive en Apps Script. Al igual que el servicio integrado de Drive de Apps Script, esta API permite que las secuencias de comandos creen, encuentren y modifiquen archivos y carpetas en Google Drive. En la mayoría de los casos, el servicio integrado es más fácil de usar, pero este servicio avanzado proporciona algunas funciones adicionales, incluido el acceso a las propiedades de archivos personalizadas y a las revisiones de archivos y carpetas.
Referencia
Para obtener información detallada sobre este servicio, consulta la documentación de referencia de la API de Google Drive. Al igual que todos los servicios avanzados de Apps Script, el servicio avanzado de Drive usa los mismos objetos, métodos y parámetros que la API pública. Para obtener más información, consulta Cómo se determinan las firmas de métodos.
/** * Uploads a new file to the user's Drive. */functionuploadFile(){try{// Makes a request to fetch a URL.constimage=UrlFetchApp.fetch('http://goo.gl/nd7zjB').getBlob();letfile={name:'google_logo.png',mimeType:'image/png'};// Create a file in the user's Drive.file=Drive.Files.create(file,image,{'fields':'id,size'});console.log('ID: %s, File size (bytes): %s',file.id,file.size);}catch(err){// TODO (developer) - Handle exceptionconsole.log('Failed to upload file with error %s',err.message);}}
Mostrar lista de carpetas
En la siguiente muestra de código, se muestra cómo enumerar las carpetas de nivel superior en el Drive del usuario. Ten en cuenta el uso de tokens de página para acceder a la lista completa de resultados.
/** * Lists the top-level folders in the user's Drive. */functionlistRootFolders(){constquery='"root" in parents and trashed = false and '+'mimeType = "application/vnd.google-apps.folder"';letfolders;letpageToken=null;do{try{folders=Drive.Files.list({q:query,pageSize:100,pageToken:pageToken});if(!folders.files||folders.files.length===0){console.log('All folders found.');return;}for(leti=0;i < folders.files.length;i++){constfolder=folders.files[i];console.log('%s (ID: %s)',folder.name,folder.id);}pageToken=folders.nextPageToken;}catch(err){// TODO (developer) - Handle exceptionconsole.log('Failed with error %s',err.message);}}while(pageToken);}
Enumera las revisiones
En el siguiente ejemplo de código, se muestra cómo enumerar las revisiones de un archivo determinado. Ten en cuenta que algunos archivos pueden tener varias revisiones y debes usar tokens de página para acceder a la lista completa de resultados.
/** * Lists the revisions of a given file. * @param {string} fileId The ID of the file to list revisions for. */functionlistRevisions(fileId){letrevisions;constpageToken=null;do{try{revisions=Drive.Revisions.list(fileId,{'fields':'revisions(modifiedTime,size),nextPageToken'});if(!revisions.revisions||revisions.revisions.length===0){console.log('All revisions found.');return;}for(leti=0;i < revisions.revisions.length;i++){constrevision=revisions.revisions[i];constdate=newDate(revision.modifiedTime);console.log('Date: %s, File size (bytes): %s',date.toLocaleString(),revision.size);}pageToken=revisions.nextPageToken;}catch(err){// TODO (developer) - Handle exceptionconsole.log('Failed with error %s',err.message);}}while(pageToken);}
Cómo agregar propiedades de archivos
En la siguiente muestra de código, se usa el campo appProperties para agregar una propiedad personalizada a un archivo. La propiedad personalizada solo es visible para la secuencia de comandos. Para agregar una propiedad personalizada al archivo que también sea visible para otras apps, usa el campo properties. Para obtener más información, consulta Cómo agregar propiedades de archivo personalizadas.
/** * Adds a custom app property to a file. Unlike Apps Script's DocumentProperties, * Drive's custom file properties can be accessed outside of Apps Script and * by other applications; however, appProperties are only visible to the script. * @param {string} fileId The ID of the file to add the app property to. */functionaddAppProperty(fileId){try{letfile={'appProperties':{'department':'Sales'}};// Updates a file to add an app property.file=Drive.Files.update(file,fileId,null,{'fields':'id,appProperties'});console.log('ID: %s, appProperties: %s',file.id,JSON.stringify(file.appProperties,null,2));}catch(err){// TODO (developer) - Handle exceptionconsole.log('Failed with error %s',err.message);}}
[[["Fácil de comprender","easyToUnderstand","thumb-up"],["Resolvió mi problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Falta la información que necesito","missingTheInformationINeed","thumb-down"],["Muy complicado o demasiados pasos","tooComplicatedTooManySteps","thumb-down"],["Desactualizado","outOfDate","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Problema con las muestras o los códigos","samplesCodeIssue","thumb-down"],["Otro","otherDown","thumb-down"]],["Última actualización: 2025-08-04 (UTC)"],[[["\u003cp\u003eThe advanced Drive service in Apps Script provides more features than the built-in service, like access to custom file properties and revisions.\u003c/p\u003e\n"],["\u003cp\u003eThis advanced service requires enabling before use and mirrors the functionality of the Google Drive API.\u003c/p\u003e\n"],["\u003cp\u003eCode samples demonstrate how to upload files, list folders and revisions, and add custom properties to files in Google Drive using this service.\u003c/p\u003e\n"],["\u003cp\u003eThe provided samples utilize version 3 of the Google Drive API and illustrate common Drive operations within Apps Script.\u003c/p\u003e\n"],["\u003cp\u003eFor comprehensive details, refer to the Google Drive API reference documentation and support guide.\u003c/p\u003e\n"]]],[],null,["The advanced Drive service lets you use the\n[Google Drive API](/drive/web) in Apps Script. Much like\nApps Script's [built-in Drive\nservice](/apps-script/reference/drive), this API allows scripts to create, find,\nand modify files and folders in Google Drive. In most cases, the built-in\nservice is easier to use, but this advanced service provides a few extra\nfeatures, including access to custom file properties as well as revisions for\nfiles and folders.\n| **Note:** This is an advanced service that must be [enabled before\n| use](/apps-script/guides/services/advanced#enable_advanced_services).\n\nReference\n\nFor detailed information on this service, see the [reference\ndocumentation](/drive/api/reference/rest/v3) for the Google Drive API. Like all\nadvanced services in Apps Script, the advanced\nDrive service uses the same objects, methods, and parameters as\nthe public API. For more information, see [How method signatures are\ndetermined](/apps-script/guides/services/advanced#how_method_signatures_are_determined).\n\nTo report issues and find other support, see the [Drive API support\nguide](/drive/api/support).\n\nSample code\n\nThe code samples in this section use [version 3](/drive/api/reference/rest/v3)\nof the API.\n\nUpload files\n\nThe following code sample shows how to save a file to a user's\nDrive. \nadvanced/drive.gs \n[View on GitHub](https://github.com/googleworkspace/apps-script-samples/blob/main/advanced/drive.gs) \n\n```gosu\n/**\n * Uploads a new file to the user's Drive.\n */\nfunction uploadFile() {\n try {\n // Makes a request to fetch a URL.\n const image = UrlFetchApp.fetch('http://goo.gl/nd7zjB').getBlob();\n let file = {\n name: 'google_logo.png',\n mimeType: 'image/png'\n };\n // Create a file in the user's Drive.\n file = Drive.Files.create(file, image, {'fields': 'id,size'});\n console.log('ID: %s, File size (bytes): %s', file.id, file.size);\n } catch (err) {\n // TODO (developer) - Handle exception\n console.log('Failed to upload file with error %s', err.message);\n }\n}\n```\n\nList folders\n\nThe following code sample shows how to list the top-level folders in the user's\nDrive. Note the use of page tokens to access the full list of\nresults. \nadvanced/drive.gs \n[View on GitHub](https://github.com/googleworkspace/apps-script-samples/blob/main/advanced/drive.gs) \n\n```gosu\n/**\n * Lists the top-level folders in the user's Drive.\n */\nfunction listRootFolders() {\n const query = '\"root\" in parents and trashed = false and ' +\n 'mimeType = \"application/vnd.google-apps.folder\"';\n let folders;\n let pageToken = null;\n do {\n try {\n folders = Drive.Files.list({\n q: query,\n pageSize: 100,\n pageToken: pageToken\n });\n if (!folders.files || folders.files.length === 0) {\n console.log('All folders found.');\n return;\n }\n for (let i = 0; i \u003c folders.files.length; i++) {\n const folder = folders.files[i];\n console.log('%s (ID: %s)', folder.name, folder.id);\n }\n pageToken = folders.nextPageToken;\n } catch (err) {\n // TODO (developer) - Handle exception\n console.log('Failed with error %s', err.message);\n }\n } while (pageToken);\n}\n```\n\nList revisions\n\nThe following code sample shows how to list the revisions for a given file. Note\nthat some files can have several revisions and you should use page tokens to\naccess the full list of results. \nadvanced/drive.gs \n[View on GitHub](https://github.com/googleworkspace/apps-script-samples/blob/main/advanced/drive.gs) \n\n```gosu\n/**\n * Lists the revisions of a given file.\n * @param {string} fileId The ID of the file to list revisions for.\n */\nfunction listRevisions(fileId) {\n let revisions;\n const pageToken = null;\n do {\n try {\n revisions = Drive.Revisions.list(\n fileId,\n {'fields': 'revisions(modifiedTime,size),nextPageToken'});\n if (!revisions.revisions || revisions.revisions.length === 0) {\n console.log('All revisions found.');\n return;\n }\n for (let i = 0; i \u003c revisions.revisions.length; i++) {\n const revision = revisions.revisions[i];\n const date = new Date(revision.modifiedTime);\n console.log('Date: %s, File size (bytes): %s', date.toLocaleString(),\n revision.size);\n }\n pageToken = revisions.nextPageToken;\n } catch (err) {\n // TODO (developer) - Handle exception\n console.log('Failed with error %s', err.message);\n }\n } while (pageToken);\n}\n```\n\nAdd file properties\n\nThe following code sample uses the `appProperties` field to add a custom\nproperty to a file. The custom property is only visible to the script. To add a\ncustom property to the file that's also visible to other apps, use the\n`properties` field, instead. For more information, see [Add custom file\nproperties](/drive/api/guides/properties). \nadvanced/drive.gs \n[View on GitHub](https://github.com/googleworkspace/apps-script-samples/blob/main/advanced/drive.gs) \n\n```gosu\n/**\n * Adds a custom app property to a file. Unlike Apps Script's DocumentProperties,\n * Drive's custom file properties can be accessed outside of Apps Script and\n * by other applications; however, appProperties are only visible to the script.\n * @param {string} fileId The ID of the file to add the app property to.\n */\nfunction addAppProperty(fileId) {\n try {\n let file = {\n 'appProperties': {\n 'department': 'Sales'\n }\n };\n // Updates a file to add an app property.\n file = Drive.Files.update(file, fileId, null, {'fields': 'id,appProperties'});\n console.log(\n 'ID: %s, appProperties: %s',\n file.id,\n JSON.stringify(file.appProperties, null, 2));\n } catch (err) {\n // TODO (developer) - Handle exception\n console.log('Failed with error %s', err.message);\n }\n}\n```"]]