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);
}
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
I am looking for a script that, once a new image file(s) is uploaded to my Google Drive (via Google Form image upload, the script will create a folder based off one of these Google Form fields (for example Name), and then move all of the images to that folder.
This is what I've cobbled together so far, but because the folder will be generated based off a field I'm not sure how this would work.
function moveFiles() {
var sourceFolder = DriveApp.getFolderById("Creative Upload (File responses)")
var targetFolder = DriveApp.getFolderById("yyyyyyy") //what should this be?
var files = sourceFolder.getFilesByType(MimeType.JPEG);
while (files.hasNext()) {
var file = files.next();
targetFolder.addFile(file);
file.getParents().next().removeFile(file);
}
}
Any suggestions would be greatly appreciated.
You need to incorporate FormApp
Create a bound script attached to your form and retrieve the latest form submission.
Retrieve the response of interest (e.g. name) and use it to create a folder with this name.
Retrieve the Id of the folder.
Retrieve the Id of the uploaded image and add the image by its Id to the newly created folder.
Sample:
function myFunction() {
var form=FormApp.getActiveForm();
var length=form.getResponses().length;
var name=form.getResponses()[length-1].getItemResponses()[0].getResponse();
var uploadedImageId=form.getResponses()[length-1].getItemResponses()[1].getResponse();
Logger.log(id);
var file=DriveApp.getFileById(uploadedImageId);
var folderId=DriveApp.createFolder(name).getId();
DriveApp.getFolderById(folderId).addFile(file);
}
To run the script automatically on every form submission - bind your function to an installable trigger onFormSubmit.
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")
}
I have a sheet on my Google Drive called "Titito." I use SpreadsheetApp.open(Titito) to open it but it returns:
ReferenceError: "Titito" is not defined. (ligne 5, fichier "macros"
When I try to open it by its URL:
SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/1NTql7GMdPg8at0VEaz2jFmzOd4zBVjwArqDqWBww_Ww/edit#gid=0');
it returns:
You do not have permission to call SpreadsheetApp.openByUrl. Required permissions:
While it's my file, created by me.
How can I open a sheet in my drive by a script in an other sheet?
I just would like to know how to do as I did it on Visual Excel (Workbooks.Open Filename:="c:\TermFB\Charges\chargecpt.xls") but on google script
Thanks.
If "Titito" is the name of the actual file, then SpreadsheetApp.open(Titito) is not the way; sa you can see in the documentation, that uses file objects. In order to get it through the name, you will need to instead use DriveApp (Documentation here). With it you can get the files in your Drive and get the one you're looking for, the code for that looks like this:
function fn(){
var files = DriveApp.getFiles();
var file;
while (files.hasNext()){
file = files.next();
if (file.getName() == "Titito")
break;
}
var ss = SpreadsheetApp.open(file).getUrl();
// rest of your code...
}
UPDATE
OP needed a way to open the actual Spreadsheet through the script, after following the instructions in this video, they were able to achieve what they wanted.
function myFunction() {
// CREATE AND OPEN A FILE CALLED Toto
var ssNew = SpreadsheetApp.create('Toto');
var tyty = ssNew.getUrl();
// var selection=SpreadsheetApp.getActiveSheet().getActiveCell().getValue();
var html = "window.open('" + tyty + "');google.script.host.close();";
var userInterface = HtmlService.createHtmlOutput(html)
SpreadsheetApp.getUi().showModalDialog(userInterface, 'Open Tab');
}
Thanks to AMolina very helpful for my first step on google script !
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.