How to Add #Tags to Files in Google Drive

H
Published in: Google Apps Script - Google Drive

Google Drive offers folders (or collections) for organizing your files but doesn’t support labels or tags. A disadvantage with folders is that a file can only belong to a single folder while multiple #tags, as in Gmail, can be assigned to a single file.

There’s a workaround though. You can assign tags to a file in Google Drive by adding them to the description of a file. A Google forum user has written this Google Script that takes the folder name in which a file is found and assigns those names as tags to the file. It works for nested folders too.

/*
 setDescriptionToFolderNames
 Workaround to fake Tags in Google Drive.
 Writes all the folder names of a file into the file description, so that the file can be found by searching the folder names.
*/

function setDescriptionToFolderNames() {

  var file;
  var filename;
  var folders;
  var filedescription;

  var contents = DocsList.getAllFiles();
  // sort ascending. Oldest first, in case of timeout:
  contents.sort(function(a,b) {return a.getLastUpdated()-b.getLastUpdated()});

  // synchronize folder names of all files (only updates if folders have changed):
  for (var i = 0; i < contents.length; i++) {
    file = contents[i];
    try {
        filename = file.getName();
        //Logger.log("Checking: " +filename +" ("+file.getLastUpdated()+")");
        folders = file.getParents();

        // sort by folder name:
        folders.sort(function(a, b)
                     { return a.getName().localeCompare(b.getName()); }
                    );
        filedescription = "";

        for (var f = 0; f < folders.length; f++) {
          filedescription = filedescription+folders[f].getName()+" ";
        }

        if (filedescription != contents[i].getDescription())
        {
          file.setDescription(filedescription);
          Logger.log("Updated: " +filename);
        }
     } catch(e){ Logger.log("Error: " +filename+" "+e); }
   }

};
Published in: Google Apps Script - Google Drive

Looking for something? Find here!

Meet the Author

Web Geek, Tech Columnist
A
Amit Agarwal

Amit Agarwal is a Google Developer Expert in GSuite and Google Apps Script. He holds an engineering degree in Computer Science (I.I.T.) and is the first professional blogger in India. Read more on Lifehacker and YourStory

Get in touch