Moving a folder (with its contents) with DriveApp - google-apps-script

DriveApp does not have a "move"-function (as of today). How can I move this folder (with all its contents as it is)?
I wish to move the source_folder (which currently resides in parent_folder)
var source_Folder = DriveApp.getFolderById(source_id);
var parent_Folder = DriveApp.getFolderById(parent_id);
and put it inside target_folder:
var target_folder = DriveApp.getFolderById(target_id);
I already have source_id,parent_id and target_id

I looked around a bit and there is similar questions/answer to this problem. I made this to (hopefully) make it easy for others with the same problem.
"Folders" in Google Drive work pretty much the same way as "Labels" in
Gmail.
You may add a folder multiple places in Google Drive. It will still be only one folder (not a copy) so its contents are available from all the places where you added the folder.
To simulate moving the source_folder, you
can:
1) first add the source_folder to the target_folder
target_folder.addFolder(source_folder);
2) remove the source_folder from its parent.
parent_folder.removeFolder(source_folder);
full example code: (note: you need the folder ID's)
function move_folder() { // id looks like this: 1XqH79csKkPMvTsCxMUzkkpURETKHJ
var source_id = "[insert_folder_id]"; // folder you wish to move
var parent_id = "[insert_folder_id]"; // where the folder is currently
var target_id = "[insert_folder_id]"; // where you want to put the folder
var source_Folder = DriveApp.getFolderById(source_id);
var parent_Folder = DriveApp.getFolderById(parent_id);
var target_Folder = DriveApp.getFolderById(target_id);
target_folder.addFolder(source_folder); // source_folder now 2 places
parent_folder.removeFolder(source_folder); // cleanup
}
how to get folder_id.
right-clicking on a folder and getting a shareable link. (the random-looking string after id=)
Get ID of newly created Folder in Google Apps Script
parent folder: DriveApp parent folder
a good answer is also found here: Implement a folder move function in Google Dirve

Related

How to create a shortcut in Google Drive Apps Script instead of multiple parents

I've been trying to read about it here: https://developers.google.com/drive/api/v3/shortcuts
And I understand the basics in shortcuts but I can't figure out how to use it in the code - the syntax.
I need to instead of placing a folder in multiple folders, placing shortcuts in those folders named the same as the original folder.
I have an original folder called Project1 placed in Drafts. Shortcuts for this folder needs to be places in Folder2/Drafts, Folder3/Drafts and Folder4/Drafts.
If I afterwards change the name of the original folder Project1 ex. to "New Building" I need to find the shortcuts in Folder 2,3 and 4 (by Id? - I can put the ID of the shortcuts in a datasheet from where I can iterate through them) - and then rename them as the original folder's new name.
And when I move the Project1 from Drafts to Confirmed. I need to move the shortcuts from Folder2/Drafts to Folder2/Confirmed etc.
This is mainly how the basic code looked like for placing the new folder
var folder1 = draft.createFolder("DRAFT - "+"Project1");
var folder1Url = folder1.getUrl();
var folder1Id = folder1.getId();
folder2Draft.addFolder(folder1);
When changing the name of the folder the name would (of course) change in the other places. But as I understand this is not the case with shortcuts. I've tested it with manually created shortcuts witch confirmed this.
The renaming part I do like this when confirming the project:
var folder1 = DriveApp.getFolderById(folder1Id);
var folder1NameOld = folder1.getName();
var folder1NameNew = folder1NameOld.replace("DRAFT - ","");
folder1.setName(folder1NameNew);
And I move the file when confirming the project with the simple:
confirmed.addFolder(folder1);
draftsFolder.removeFolder(folder1);
The script is made in a spreadsheet and I already put alle the folderIDs in a data sheet in the file so I can very easy make references to the different folders and if needed also collect the IDs of the shortcuts to be able to rename them.
Update:
To make a more clear question:
How to do this with shortcuts instead of multi-parenting?
function shortcut() {
var s = SpreadsheetApp.getActive();
var sheet = s.getActiveSheet();
var projectFolderId = sheet.getRange('B1').getValue();
var folder1DraftId = sheet.getRange('B2').getValue();
var folder2DraftId = sheet.getRange('B3').getValue();
var folder1 = DriveApp.getFolderById(projectFolderId);
DriveApp.getFolderById(folder1DraftId).addFolder(folder1);
DriveApp.getFolderById(folder2DraftId).addFolder(folder1);
}
I believe your goal is as follows.
You want to achieve the following script as the shortcut.
function shortcut() {
var s = SpreadsheetApp.getActive();
var sheet = s.getActiveSheet();
var projectFolderId = sheet.getRange('B1').getValue();
var folder1DraftId = sheet.getRange('B2').getValue();
var folder2DraftId = sheet.getRange('B3').getValue();
var folder1 = DriveApp.getFolderById(projectFolderId);
DriveApp.getFolderById(folder1DraftId).addFolder(folder1);
DriveApp.getFolderById(folder2DraftId).addFolder(folder1);
}
At above script, folder1 is put in the folders of folder1DraftId and folder2DraftId.
For this, how about this answer?
Modification points:
In this case, the method of files.create in Drive API is used. But in the current stage, the method of Files: insert in Drive API v2 can also create the shortcut. So in this answer, Drive API v2 of Advanced Google services is used.
Modified script:
When your script is modified, it becomes as follows. Before you run the script, please enable Drive API at Advanced Google services.
From:
var folder1 = DriveApp.getFolderById(projectFolderId);
DriveApp.getFolderById(folder1DraftId).addFolder(folder1);
DriveApp.getFolderById(folder2DraftId).addFolder(folder1);
To:
const folderIDs = [folder1DraftId, folder2DraftId];
folderIDs.forEach(f => {
Drive.Files.insert({
shortcutDetails: {targetId: projectFolderId},
parents: [{id: f}],
title: DriveApp.getFolderById(projectFolderId).getName(),
mimeType: "application/vnd.google-apps.shortcut"
});
});
References:
Advanced Google services
Create a shortcut to a Drive file
Files: insert of Drive API v2
The official document says as follows.
Note: Apps creating shortcuts with files.insert must specify the MIME type application/vnd.google-apps.drive-sdk.
But, when application/vnd.google-apps.drive-sdk is used, the shortcut couldn't be created. I'm not sure whether this is the bug or the current specification. So I used application/vnd.google-apps.shortcut as the mimeType.

Showing thumbnails in a Google sheet [duplicate]

This question already has answers here:
How to get the file URL from file name in Google Sheets with correct Authorization via custom function/script
(3 answers)
Closed 4 years ago.
The code below generates the IMAGE function for the sheet to show thumbnails of all (PDF) files in a chosen folder, obtained with a URL and the file ID:
function scannedMail() {
var files, file, sheet;
sheet = SpreadsheetApp.getActive().getSheetByName('ScannedMail');
files = DriveApp.getFoldersByName("ScannedMail").next().searchFiles('');
var i = 1;
while (files.hasNext()) {
var file = files.next();
var ID = file.getId();
sheet.getRange('A' + i).setValue("=IMAGE(\"https://drive.google.com/thumbnail?authuser=0&sz=w320&id=" + ID + "\"\)");
sheet.getRange('B' + i).setValue(file.getName());
i=i+1;
}
}
Yet it does not show the thumbnails. I found out that it shows just the ones where I manually retrieved the ID from getting a "shareable link". Apparently this ensures the right share settings to get the thumbnails of my own files.
1) Is the previous assumption correct, and why do I need to adapt share settings somehow, where I have read other files without any issues?
2) How can I adapt the script to adapt the share settings, or make it work otherwise?
The script is meant to operate just within my own Google account, and to keep the files private.
I tried sharing the folder with myself, but that does not make a difference (or sense). Is the script somehow regarded as being another user than myself?
Following suggestions from #Rubén and #Cooper, I have tried using insertImage either based on a URL:
sheet.insertImage(file.thumbnailLink, 1, i)
or based on a blob:
sheet.insertImage(file.getThumbnail(), 1, i)
But the most I could get out of Google was "We're sorry, a server error occurred. Please wait a bit and try again", with the code below:
function ScannedMail() {
var files, file, , name, blob, sheet;
sheet = SpreadsheetApp.getActive().getSheetByName('ScannedMail');
files = DriveApp.getFoldersByName("ScannedMail").next().searchFiles('');
var i = 1;
while (files.hasNext()) {
file = files.next();
name = file.getName(); //not needed, just for debugging
blob = file.getThumbnail();
sheet.insertImage(blob, 1, i); // it runs up to here...
i = i + 1;
}
}
The code execution gets stuck on the first occurrence of insertImage().
So we have 3 approaches (IMAGE function in sheet, insertImage(URL,1,1), and insertImage(blob,1,1)) but all 3 do not make a thumbnail appear, apart from the first method when you make the file public (not a serious option).
I don't see a duplicate question and answer that helps me find out what is wrong with my code, or helps me to somehow get the required thumbnails in the spreadsheet. The kindly proposed solutions did not succeed in that yet.
Try something like this:
function imgArray() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('ImageArray');
if(!sh){
sh=ss.insertSheet('ImageArray');
}
var imgA=[];
var folder=DriveApp.getFolderById('folderid');
var files=folder.getFiles();
while(files.hasNext()){
var file=files.next();
var filename=file.getName();
imgA.push(file.getBlob());
}
for(var r=0;r<imgA.length;r++){
sh.insertImage(imgA[r],1,r+1);
}
}
This was adapted from an answer from #Tanaike.
I guess this is what you were looking for:
function ScannedMail() {
var sheet = SpreadsheetApp.getActive().getSheetByName('ScannedMail');
var files = DriveApp.getFoldersByName("ScannedMail").next().searchFiles('');
var i = 1;
while (files.hasNext()) {
var file = files.next();
var blob = file.getBlob();
sheet.insertImage(blob, 1, i); // it runs up to here...
i = i + 1;
}
}
Google Sheets IMAGE built-in function only is able to retrieve images that are publicly available, so, yes you should have to adapt the sharing settings to make the images viewable by anyone.
In order to keep the files private you should not use IMAGE built-in function, you could use one of the methods of Class Sheet to insert images like insertImage(blobSource,column,row). See answer to Adding Image to Sheet from Drive for an example.
NOTES:
As custom functions run anonymously they can't be used them either.
According to Mogsdad answer to InsertImage(url,x,y) doesn't work with Google Drive insertImage(url,row,column) can't be used to insert images from Google Drive
Related
Image function or .insertImage not working for Google Apps Script and Sheets
What is the right way to put a Drive image into a Sheets cell programmatically?

Google Code (Drive) createFile in parent folder/overwrite existing file in parent folder

so i created a simple google code that exports sheet to json, and I'm wondering if there's a simple way to:
Export the file to the same folder where the sheet that script running it is in,
Overwrite the file if it already exists (also in the same folder the sheet script is in)
cheers
There's no easy way, but here's how (I assume you're using Apps Script):
Get the file id of your spreadsheet https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet#getId()
Get its parent folders - there can be more than one - https://developers.google.com/apps-script/reference/drive/file#getParents()
See if there are existing files with the name - there can be more than one - https://developers.google.com/apps-script/reference/drive/folder#getFilesByName(String)
If it exists set its content https://developers.google.com/apps-script/reference/drive/file#setcontentcontent
If it doesn't exist create it - https://developers.google.com/apps-script/reference/drive/folder#createfilename-content
thanx to Ian for research links, made it work :)
here's the snippet if anyone else is needing the same thing
var _ID = SpreadsheetApp.getActiveSpreadsheet().getId();
var _sheet = SpreadsheetApp.getActiveSpreadsheet();
var _file = DriveApp.getFolderById(_ID);
var _folder = _file.getParents().next();
var _parentFolder = _file.getParents().next();
var _existingJsons = _parentFolder.getFilesByName(sheet.getName()+".json");
// if .json with the same name already exists in this directory, just overwrite content
if (_existingJsons.hasNext()){
while (_existingJsons.hasNext() ){
var _json = _existingJsons.next();
_json.setContent(output);
Logger.log(_json.getName());
}
}
// if not, create new one, and move it in the same folder sheet is in
else {
var _json = DriveApp.createFile(sheet.getName()+".json", output, MimeType.PLAIN_TEXT);
_json.makeCopy(_parentFolder);
_json.setTrashed(true);
}

Merge folder with the same name in google drive using google script

Who knows how to merge folder with the same name in google drive using google script?
Step 01: Find if any duplicate folder in the root-Folder;
Step 02: If yes, choose one folder as main-folder, and then move all files in the other folder(with the same name) to this main-folder;
Step 03: Delete the other folder(with the same name).
Many thanks in advance.
Merge Folder with the same name under the same Folder
My approach:
Take parent folder in which you want to check for folders with same name
Loop over all subfolders and get their names
Find all folders within parent folder with each found folder name
Specify first iteration for given folderName as destination folder
If there is more than one folder with given name, move all files and folders from this folder to destination folder and trash that folder
Try this:
I have succesfully tested this function on some junk data.
function mergeDuplicateFolders() {
var parentFolder = DriveApp.getFolderById('{paste your folder ID here}'); //parent folder which will be scanned for duplicates
var childFolderIterator = parentFolder.getFolders(); //all folders within parent folder
//iteration over all folders in parent directory
while (childFolderIterator.hasNext()) {
var childFolder = childFolderIterator.next();
var childFolderName = childFolder.getName();
var childSameNameIterator = parentFolder.getFoldersByName(childFolderName);
//just check if folder with givn name exist (there should be at least one)
if(childSameNameIterator.hasNext()) {
var destFolder = childSameNameIterator.next();
//iteration over 2nd and all other folders with given name
while (childSameNameIterator.hasNext()) {
var toMergeFolder = childSameNameIterator.next();
var filesToMove = toMergeFolder.getFiles();
var foldersToMove = toMergeFolder.getFolders()
//iteration over all files
while (filesToMove.hasNext()) {
var file = filesToMove.next();
moveFile(file, destFolder);
}
//iteration over all subfolders
while (foldersToMove.hasNext()) {
var folder = foldersToMove.next();
moveFolder(folder, destFolder);
}
//trashes empty folder
toMergeFolder.setTrashed(true);
}
}
}
}
//custom function which removes all parents from speciefied file and adds file to new folder
function moveFile(file, destFolder) {
var currentParents = file.getParents();
while (currentParents.hasNext()) { // be careful, this loop will remove all parents from the file... if you want to have this file in multiple folders you should add if statement to remove it only from specified folder
var currentParent = currentParents.next();
currentParent.removeFile(file);
}
destFolder.addFile(file);
Logger.log("File moved to " + destFolder.getName());
}
//custom function which removes all parents from speciefied folder and adds that folder to new one
function moveFolder(folder, destFolder) {
var currentParents = folder.getParents();
while (currentParents.hasNext()) { // be careful, this loop will remove all parents from the folder... if you want to have this folder in multiple folders you should add if statement to remove it only from specified folder
var currentParent = currentParents.next();
currentParent.removeFolder(folder);
}
destFolder.addFolder(folder);
Logger.log("Folder moved to " + destFolder.getName());
}
Your application:
You can of course edit first two lines of this function and add parentFolderId as parameter of that function. Then you can use this function in your own iteration and check multiple folders for duplicates.
function mergeDuplicateFolders(parentFolderId) {
var parentFolder = DriveApp.getFolderById(parentFolderId);
//...continue with the code from above
Warnings
Be careful. In Google Drive you can have one file in multiple folders.
This code will remove files (in folders with same name) from all
parent folders and moves them only in one. If you prefere removing it
only from the folder with same name, you need to add some if statement
in moveFolder() and moveFile() functions.
Google script allows to run custom function only for (approx.) 6 minutes. If you have large amout of folders to check, you should make some workaround. You can add e.g. execution time limit. Example is here: Prevent Google Scripts from Exceeding the Maximum Execution Time Limit
EDIT:
Of course there is much simpler way to remove file only frome merged folder... Remove both custom functions and edit both iterations this way... I didn't realize it first.
//iteration over all files
while (filesToMove.hasNext()) {
var file = filesToMove.next();
toMergeFolder.removeFile(file);
destFolder.addFile(file);
}
//iteration over all subfolders
while (foldersToMove.hasNext()) {
var folder = foldersToMove.next();
toMergeFolder.removeFolder(folder);
destFolder.addFolder(folder);
}
Class Folder, currently, doesn't have existing method to move files from one folder in Google Drive to another.
And as far as I know, there is an existing issue on Seeing duplicate files after sync on desktop Drive version 1.14. However, you may follow the given workaround in the forum as follows:
Step 01:
How to Find duplicates files (by name and/or size) in a specific folder of my google drive
Step 02:
How do I copy & move a file to a folder in Google Apps Script?
Step 03: You can use removeFolder(child) method from Class Folder, which can only be used to remove a given folder from a current folder.
I hope that helps.

issu DriveApp not move file

The following code should create a folder called "prova" inside the folder with id "0B9nV49psIf6LUUJpa0JDZ1dNQnM"
function createFolder() {
var idFolderDestination = "0B9nV49psIf6LUUJpa0JDZ1dNQnM";
var folderDestination = DriveApp.getFolderById(idFolderDestination);
var file = folderDestination.createFolder("prova");
}
The result of the function is that the folder named "prova" is correctly created but does not move inside the folder with id "0B9nV49psIf6LUUJpa0JDZ1dNQnM". Remains in My Drive.
This was reported as an issues and has since been marked as resolved.