Is it possible to use Google Apps Script to search Google Drive for both documents and folders?
Google have killed their own docs/drive search gadget as it appears to rely on iGoogle and Google Enterprise support have admitted this.
Thank you
I think you are looking for SearchFile and SearchFolder of the DriveApp.
The full list of parameters is available in the Google Drive SDK documentation
I've run some tests and seems like it's not possible to do 1 search and get files and folders like it's possible calling the search function from the Google Drive API.
Here a code that list the files and folders with a title that have 2013 in it
function myFunction() {
var searchFor ='title contains "2013"';
var names =[];
var files = DriveApp.searchFiles(searchFor);
while (files.hasNext()) {
var file = files.next();
names.push(file.getName());
}
var folders = DriveApp.searchFolders(searchFor);
while (folders.hasNext()) {
var file = folders.next();
names.push(file.getName());
}
for (var i=0;i<names.length;i++){
Logger.log(names[i]);
}
}
Try this piece of code
function searchDrive() {
var folderToSearch = "FolderName";
var folders = DriveApp.getFoldersByName(folderToSearch);
Logger.log(folders);
var fileToSearch = "fileName";
var files = DriveApp.getFilesByName(fileToSearch);
Logger.log(files);
}
This example can be found here.
Related
I have some code below that takes all the tabs (excluding 2 of them) in a Google Sheets file and creates independent Google Sheets files for each of them. Right now, they are saving by default in root folder (My Drive), but I would like them to be created in the same active folder as the file from which I call my Google Apps Script. Does anyone know how I can do that with the below code? I also want to avoid scenarios where it's created first in My Drive and then moved to the Shared Drive. The reason for this is because other people may run this code and I want to avoid an instance where the folder in My Drive needs to be updated in the code based on who runs this script.
The simplified version of my above paragraph for brevity: How can I adapt the below code so that the Google Sheets files that are created show up in the active Google Shared Drive folder? I will enabling the Drive API.
My Current Code:
function copySheetsToSS(){
var ss = SpreadsheetApp.getActive();
for(var n in ss.getSheets()){
var sheet = ss.getSheets()[n];
var name = sheet.getName();
if(name != 'ControlTab' && name != 'RawData'){
var alreadyExist = DriveApp.getFilesByName(name);
while(alreadyExist.hasNext()){
alreadyExist.next().setTrashed(true);
}
var copy = SpreadsheetApp.create(name);
sheet.copyTo(copy).setName(name);
copy.deleteSheet(copy.getSheets()[0]);
}
}
}
In your situation, when your script is modified, how about the following modification?
Modified script:
In this modification, Drive API is used. So, please enable Drive API at Advanced Google services.
function copySheetsToSS() {
var ss = SpreadsheetApp.getActive();
var folderId = DriveApp.getFileById(ss.getId()).getParents().next().getId();
for (var n in ss.getSheets()) {
var sheet = ss.getSheets()[n];
var name = sheet.getName();
if (name != 'ControlTab' && name != 'RawData') {
var alreadyExist = DriveApp.getFilesByName(name);
while (alreadyExist.hasNext()) {
alreadyExist.next().setTrashed(true);
}
var newSS = Drive.Files.insert({ title: name, mimeType: MimeType.GOOGLE_SHEETS, parents: [{ id: folderId }] }, null, { supportsAllDrives: true });
var copy = SpreadsheetApp.openById(newSS.id);
sheet.copyTo(copy).setName(name);
copy.deleteSheet(copy.getSheets()[0]);
}
}
}
In this modification, first, the parent folder of Spreadsheet is retrieved. And, in the loop, the new Spreadsheet is created to the specific folder using Drive API.
Note:
In this case, it is required to have the write permission of the folder. Please be careful about this.
References:
getFileById(id)
getParents()
Files: insert
The issue : I have multiple documents ( specifically, Google Sheets ) in multiple Shared Drives that need the same single word replaced. Some searching around this forum found me the following code, but it doesn't seem to be working. I'm not getting any error messages, but when I go check the files nothing has been changed. I checked and made sure I put in my search string and replacement string correctly.
Do I need to do something different to get it to check files in Shared Drives? I tried turning on the Drive API in Advanced Google Services, but that just gave me an error in line 6 (
var doc = DocumentApp.openById(file.getId()); )
Here's the code I was using :
function myFunction() {
var files = DriveApp.getFiles(); // Note: this gets *every* file in your Google Drive
while (files.hasNext()) {
var file = files.next();
Logger.log(file.getName());
var doc = DocumentApp.openById(file.getId());
doc.replaceText("My search string or regex", "My replacement string");
}
Logger.log("Done")
}
DriveApp.getFiles() returns only the files on "My Drive". In order to be able to get the files in a Shared Drive (formerly Team Drive) you have to enable the Drive Advanced Service and, instead of
var files = DriveApp.getFiles();
use something like
var files = Drive.Files.list(options);
Related
Finding shared date of a file in GAS
Google Apps Script TeamDrive DriveApp.searchFolders and DriveApp.searchFiles does not return any results
"Shared Drive" support in Google Apps Script
In order to access the shared drives, you need to activate the Drive API in the Advanced Google Services, but in order to access it, you will have to use Drive and not DriveApp.
If you want to retrieve the shared drives specifically and look for files with a certain name, you can try this:
Code
// Copyright 2020 Google LLC.
// SPDX-License-Identifier: Apache-2.0
function retrieveFiles() {
var allDrives = Drive.Drives.list().items;
let fileName = 'FILE_NAME';
for (let i = 0; i < allDrives.length; i++) {
var driveId = allDrives[i].id;
console.log(id)
var optionalArgs = {
'driveId': driveId,
'includeItemsFromAllDrives': true,
'corpora': 'drive',
'supportsAllDrives': true,
'q': "title=" + "'" + fileName + "'"
};
var filesReturned = Drive.Files.list(optionalArgs).items;
for (let j = 0; j < filesReturned.length; j++) {
var fileId = filesReturned[j].id;
var sheet = SpreadsheetApp.openById(fileId);
//sheet manipulation
}
}
}
Explanation
The above code retrieves all the shared drives by making use of the Drives:list method and then for each shared drive, searches for all the files which are named FILE_NAME using Files:list. Then, it accesses each file by using SpreadsheetApp.
Note
Please bear in mind that the code can be customized in order to fit your needs and requirements specifically.
Reference
Drive API Drives:list;
Drive API Files:list;
Advanced Google Services Apps Script;
SpreadsheetApp Class Apps Script.
I have a Google Apps script that moves a Google Drive file to another Google Drive map. This happens every 4 hours because of a time-based trigger. Does anyone know which file it chooses to move? The files have a random name so should be moved randomly. However, it seems the scripts only moves the last uploaded files.
For context: I use the script in combination with IFTTT for this Twitter account.
var files = DriveApp.getFolderById("SourceFolderId").getFiles();
{
var file = files.next();
var destination = DriveApp.getFolderById("TargetFolderId");
destination.addFile(file);
var pull = DriveApp.getFolderById("SourceFolderId");
pull.removeFile(file);
}
}
Try this:
function moveRandomly(s,t) {
var files=DriveApp.getFolderById(s).getFiles();
var fA=[];
while(files.hasNext()){fA.push(files.next().getId());}
var file=DriveApp.getFileById(fA[Math.floor(Math.random()*fA.length)]);
var destination=DriveApp.getFolderById(t);
destination.addFile(file);
var pull=DriveApp.getFolderById("SourceFolderId");
pull.removeFile(file);
}
Background: I have about 1500 Google Docs in a Google Services account shared directory. Some of those docs have hyperlinks. I need to replace the URL in hyperlinks with new URLs using a Google Script.
I found this script here. The script below will successfully replace URL's within the body of any Google Doc in my drive, but it will not replace any URL's within hyperlinks.
How can I modify this script to replace the URL within a hyperlink instead of just the body text?
var files = DriveApp.getFiles(); // Note: this gets *every* file in your Google Drive
while (files.hasNext()) {
var file = files.next();
Logger.log(file.getName());
var doc = DocumentApp.openById(file.getId());
doc.replaceText("http://www.googledoclink1.com", "http://www.googledoclinkA.com");
doc.replaceText("http://www.googledoclink2.com", "http://www.googledoclinkB.com");// Note: This will be repeated probably 500 times
}
Logger.log("Done")
}
You need to replace both the text and the hyperlink separately
The hyperlink can be modified with setLinkUrl().
Modify your code in a following way to make it work:
function myFunction() {
var oldLink="http://www.googledoclink1.com";
var newLink="http://www.googledoclinkA.com";
var oldLink2="http://www.googledoclink2.com";
var newLink2="http://www.googledoclinkB.com";
var files = DriveApp.getFiles(); // Note: this gets *every* file in your Google Drive
while (files.hasNext()) {
var file = files.next();
Logger.log(file.getName());
var doc = DocumentApp.openById(file.getId());
var link=doc.getBody().findText(oldLink).getElement().asText();
var link2=doc.getBody().findText(oldLink2).getElement().asText();
link.setLinkUrl(newLink);
doc.replaceText(oldLink, newLink);
link2.setLinkUrl(newLink2);
doc.replaceText(oldLink2, newLink2);
}
Logger.log("Done")
}
Is there any way to fetch files name without their extensions from a Google Drive folder into Google spreadsheet?
Yes, take a look to this.
In the page's example, you can switch DriveApp.getFiles() by myFolder.getFiles(), like this:
var myFolder = DriveApp.getRootFolder();
var files = myFolder.getFiles();
while (files.hasNext()) {
var file = files.next();
Logger.log(file.getName());
}