Move all files from one folder - google-apps-script

I'm super bad in apps script in Google drive ... I'm upset.
I need your help.
I have folders like this in my root drive :
students
__kev
___math
___english
__donald
___math
___english
__tony
___math
___english
transfer
__math
I want to automate an operation: copy or move all the contents of the "transfer" folder to each student folder.
I can do this task easily on PowerShell or bash with a sync client but I need it directly on drive now.
Any idea ? I want to add a menu on a file with the tool script.

The algorithm is quite simply, but there is one trick. You need to decide what should the script do in case a destination folder already has a file with the same name. By default Google Drive allows to have many files with the same name within a folder, which can be confusing.
My script checks a target folder and removes a file with the same name (it's supposed that there is one file) before copying.
function main() {
const root_folder_ID = "###"; // here is ID of your folder
const root_folder = DriveApp.getFolderById(root_folder_ID);
const transfer_folder = root_folder.getFoldersByName("transfer").next(); // transfer folder
// get array of subjects from transfer folder
const subjects_generator = transfer_folder.getFolders();
var subjects = [];
while (subjects_generator.hasNext()) {
var subj = subjects_generator.next();
subjects.push(subj);
}
// get students folders (a generator)
const students_folder = root_folder.getFoldersByName("students").next();
const students = students_folder.getFolders();
// copy all subject folders (with content) into students folders
while(students.hasNext()) {
var student = students.next();
for (var s in subjects) {
Logger.log("folder '" + subjects[s] + "' started to copy to '" + student + "'");
copy_folder(subjects[s], student);
Logger.log("---");
}
}
}
function copy_folder(source_folder, target_folder) {
// pick or create subject subfolder within target folder
try {
var subfolder = target_folder.getFoldersByName(source_folder.getName()).next();
} catch(e) {
var subfolder = target_folder.createFolder(source_folder.getName());
}
// get all files from source folder
var files = source_folder.getFiles();
// copy the files into the subfolder
while(files.hasNext()) {
var file = files.next();
var file_name = file.getName();
// try to remove old file with the same name in the target folder
try {
var old_file = subfolder.getFilesByName(file_name).next();
old_file.setTrashed(true);
Logger.log("old file '" + old_file + "' was removed")
} catch(e) {}
file.makeCopy(file.getName(), subfolder);
Logger.log("file '" + file + "' is copied")
}
}
To run this script you have to create a new document somewhere on Google Drive, go the menu 'Tools' and click on 'Script Editor'.
Then you need to paste the text of the script into the editor and click the 'Run' icon:
But first you need to paste your folder ID into the second line of the script of course.
Alternatively you can make a custom menu in your document and run the script from there, without Script editor.
To make a custom menu just add this function at the end (or start) of the script in Script editor:
// custom menu
function onOpen() {
DocumentApp.getUi().createMenu('Scripts')
.addItem('📁 Copy files', 'main')
.addToUi();
}
And you'll get the custom menu 'Script' after reload your document:

This should fit your needs. Adapted from: this site. Change the id's of the two folders.
function start() {
var transfertFolder = DriveApp.getFolderById("xxxxxxx-YhSCZXh1PDeqpE8mXjHHJJF");
var studentFolder = DriveApp.getFolderById("xxxxxxx_cQgd3DZV9Ukt4yI_-jTS_86Z").getFolders();
while (studentFolder.hasNext()){
const student = studentFolder.next()
copyFolder(transfertFolder,student)
}
}
function copyFolder(source, target) {
var folders = source.getFolders();
var files = source.getFiles();
while (files.hasNext()) {
var file = files.next();
file.makeCopy(file.getName(), target);
}
while (folders.hasNext()) {
var subFolder = folders.next();
var folderName = subFolder.getName();
var targetFolder = target.createFolder(folderName);
copyFolder(subFolder, targetFolder);
}
}

Related

Google Apps - How to get all files name from current directory?

How I can get all files name from current directory?
I have a code
function showAllFollderFronRoot() {
// get all files from the ROOT folder
var files = parentFolder;
while (files.hasNext()) {
var file = files.next();
// Logger.log(file.getName());
DocumentApp.getUi().alert(file.getName());
}
}
But it work only with ROOT dir.
How I can get all file names in array in current dir?
UPDATE:
I have a file structure: MT/MT.100-107/MT.100-1007.1001.doc
I need make code, if somebody open New Template from Docs - script need automatically safe this file with true structure - with next filename + 1 (example MT.100-1007.1002.doc, next new file from Template - MT.100-1007.1003.doc ...)
Script need to find all filenames => show last bigger count (1002.doc) => count + 1 => save this file with new filename MT.100-1007.1003.doc
My code work, but it make tmp file in Root dir & not work perfect, because it not calculate last bigger count in current dir and if I delete file, example MT.100-1007.1003.doc in dir MT, and make new file in dir UA - count be MT.100-1007.1004.doc no matter what the names of the files are in the folder UA.
These script with mistakes, how I can fix it?
/**
* #OnlyCurrentDoc
*/
function saveFilename() {
// Get current file name
const ui = DocumentApp.getUi(),
doc = DocumentApp.getActiveDocument(), //Added
thisFileId = doc.getId(),
thisFileName = doc.getName();
const thisFile = DriveApp.getFileById(thisFileId);//Modified from getFolderById
const parentFolder = thisFile.getParents();
const currentFolder = parentFolder.next();//Modified from currentFolderName
const currentFolderName = currentFolder.getName();//Added
//ui.alert(currentFolderName);
/*Store a init file in root to getLatestFileNumber*/
var initIter = DriveApp.getFilesByName(currentFolderName + 'init00'),
initBool = initIter.hasNext(),
init;
if (!initBool) {
init = DriveApp.createFile(currentFolderName + 'init000', '0');
} else {
init = initIter.next();
}
/*Get current Number and format it to 4 digits*/
var currentNum = init.getBlob().getDataAsString() * 1 + 1,
formatNum = ('0000' + currentNum).substr(-3);
/*If filename already contains folderName, do nothing*/
if (!(thisFileName.search(currentFolderName) + 1)) {
doc.setName(currentFolderName +'.' + formatNum).saveAndClose();
init.setContent(currentNum);
}
// delete TMP file from ROOT dir
DriveApp.getFileById(init.getId()).setTrashed(true)
}
You want to retrieve filenames of all files in the parent folder of the active document.
If my understanding is correct, how about this answer?
Flow:
The flow of this script is as follows.
Retrieve file ID of the active document.
Retrieve parent folder ID of the active document.
Retrieve files in the parent folder ID.
Retrieve filenames of files.
Modified script:
function showAllFollderFronRoot() {
var fileId = DocumentApp.getActiveDocument().getId();
var parentFolderId = DriveApp.getFileById(fileId).getParents().next().getId();
var files = DriveApp.getFolderById(parentFolderId).getFiles();
while (files.hasNext()) {
var file = files.next();
Logger.log(file.getName())
}
}
Note:
This sample script supposes as follows.
The parent of the active document is only one.
All files in the parent folder of the active document are retrieved. But the folders are not retrieved.
References:
getId()
getParents()
getFolderById(id)
getFiles()
If I misunderstand your question, please tell me. I would like to modify it.
I fix this problem, but idk how to parse last 4 digits in filename and find MAX from it. Do you have any idea? method slice(4) not working in apps script :(
function currFiles() {
const ui = DocumentApp.getUi(),
doc = DocumentApp.getActiveDocument(),
thisFileId = doc.getId(),
thisFileName = doc.getName();
const thisFile = DriveApp.getFileById(thisFileId);
const parentFolder = thisFile.getParents();
const currentFolder = parentFolder.next();
const currentFolderName = currentFolder.getName();
const currentFolderId = currentFolder.getId();
// get all files in currentFolder
var folderId = currentFolderId;
// Log the name of every file in the folder.
var files = DriveApp.getFolderById(folderId).getFiles();
while (files.hasNext()) {
var file = files.next();
Logger.log(file.getName());
}
}

Simplify this code? Get all files from folder & it's subfolders-- Current code is timing out

I have a drive folder that's got about 1500 Google Slides within one parent folder, and multiple child folders. I've been using this script, but it's stopped working because it times out (our folders have grown considerably). Is there any easy way around this? I'm needing links to all of these files populated (with their file names) onto ONE tab of a Google Sheet.
Here's my current script (got it from somewhere online and modified it a bit; I am not super experienced/trained with writing code).
var folderId = '1TO3e8ilnqNuxBcvTw8D_3RsDxDzMwvX7';
// Main function 1: List all folders, & write into the current sheet.
function listFolders() {
getFolderTree(folderId, false);
}
// Main function 2: List all files & folders, & write into the current sheet.
function listAll() {
getFolderTree(folderId, true);
}
// =================
// Get Folder Tree.
function getFolderTree(folderId, listAll) {
try {
// Get folder by id.
var parentFolder = DriveApp.getFolderById(folderId);
// Initialise the sheet.
var file, data, sheet = SpreadsheetApp.getActiveSheet();
sheet.clear();
// Get files and folders
getChildFolders(parentFolder.getName(), parentFolder, data, sheet, listAll);
} catch (e) {
Logger.log(e.toString());
}
}
// Get the list of files and folders and their metadata in recursive mode.
function getChildFolders(parentName, parent, data, sheet, listAll) {
var childFolders = parent.getFolders();
// List folders inside the folder.
while (childFolders.hasNext()) {
var childFolder = childFolders.next();
// Logger.log("Folder Name: " + childFolder.getName());
data = [
parentName + "/" + childFolder.getName(),
childFolder.getName(),
];
// List files inside the folder.
var files = childFolder.getFiles();
while (listAll & files.hasNext()) {
var childFile = files.next();
// Logger.log("File Name: " + childFile.getName());
data = [
childFile.getUrl(),
childFile.getName(),
];
// Write
sheet.appendRow(data);
}
// Recursive call of the subfolder
getChildFolders(parentName + "/" + childFolder.getName(), childFolder, data, sheet, listAll);
}
}

Google Apps Script Triggers not working (List Files and Folders within Gdrive Folder)

So I created my first script by copying and pasting stuff from others. Somewhere down the line it look like I removed something that allows for triggers (both time & onchange) to work.
I tried applying some suggestions from other questions like these but without result..
function DolistFilesInFolder() {
listFilesInFolder("specified folder"); //Enter folder name in between " "
}
function listFilesInFolder(folderName) {
Logger.log(folderName);
var folders = DriveApp.getFoldersByName(folderName);
var folder = folders.next();
var contentfolders = folder.getFolders(); //fetches the folders inside the folder
var contentfiles = folder.getFiles(); //fetches the files inside the folder
// Find or add sheet with folder name
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName(folderName);
if (sheet) {
Logger.log("found");
}
else {
sheet = ss.insertSheet(folderName);
}
sheet.clear();
sheet.appendRow(["Name", "Date", "URL"]);
// Loop over folders in folder, using file iterator
while (contentfolders.hasNext()) {
var file = contentfolders.next();
var data = [
file.getName(),
file.getDateCreated(),
file.getUrl()
];
sheet.appendRow(data);
// Loop over files in folder, using file iterator
while (contentfiles.hasNext()) {
var file = contentfiles.next();
var data = [
file.getName(),
file.getDateCreated(),
file.getUrl()
];
sheet.appendRow(data)
}}
}
*For anyone interested this script lists both the Files and Folders in a Google Sheet based on the "specified folder"

I'm trying to create a tree from a folder in Google Drive, but I don't get any output

I'm trying to modify from this code to list files and folders in a specific folder, rather than all folders:
/* Change the FOLDER NAME to generate tree for any specify folder */
function generateFolderTree() {
try {
// If you want a tree of any sub folder
var parent = DriveApp.getFoldersByName('TitaniumBackup').next();
// If you want to search from the top (root) folder
//var parentFolder = DriveApp.getRootFolder();
getChildFolders(parent);
} catch (e) {
Logger.log(e.toString());
}
}
function getChildFolders(parent) {
var childFolders = parent.getFolders();
while (childFolders.hasNext()) {
var childFolder = childFolders.next();
Logger.log("Folder Name: " + childFolder.getName());
Logger.log("Folder URL: " + childFolder.getUrl());
var files = childFolder.getFiles();
while (files.hasNext()) {
// Print list of files inside the folder
Logger.log(files.next().getName());
}
// Recursive call for any sub-folders
getChildFolders(childFolder);
}
}
But when I run it, and after giving the authorization, I don't see any html file inside my drive. Why?
I'm trying to modify from this code:
https://ctrlq.org/code/19923-google-drive-files-list
The Script doesn't create an HTML file. The results are written on the Google Apps Script log, using the Basic Logging. Basically once your script ran, click View > Logs.

Moving Files In Google Drive Using Google Script

I'm trying to create documents using information posted through Google forms, then once the document is created I would like to move the document into a shared folder for people to view.
At the moment I have the script taking all of the information from the Google Forms linked spreadsheet.
Using that information I'm using the following code to create the document:
var targetFolder = DriveApp.getFolderById(TARGET_FOLDER_ID);
var newDoc = DocumentApp.create(requestID + " - " + requestSummary);
This is creating the document successfully in my Google Drive root folder, but I can't seem to move it where I want to move it to.
I've seen a lot of posts suggesting use stuff like targetFolder.addFile(newDoc) but that doesn't work, similarly I've seen examples like newDoc.addToFolder(targetFolder) but again this isn't working for me.
It seems that all the online questions people have already asked about this are using the previous API versions that are no longer applicable and these methods do not apply to the new DriveApp functionality.
What I would like, if possible, is to create the new document as above so that I can edit the contents using the script, then be able to move that file to a shared folder. (From what I understand there is no 'move' function at present, so making a copy and deleting the old one will suffice).
If we make a copy of the file and trash the original, it would change the file URL and also the file sharing settings won't be preserved.
In Drive, it is possible to add a file to multiple folders with the .addFolder() method of DriveApp service. You can add the file to the target folder and then remove the file from the immediate parent folder.
function moveFiles(sourceFileId, targetFolderId) {
var file = DriveApp.getFileById(sourceFileId);
var folder = DriveApp.getFolderById(targetFolderId);
file.moveTo(folder);
}
This is my first post! I know this has been answered a few times, but I actually came across this question while working on my project, and while reviewing the Apps Script documentation, I figured out a concise way to do it. A variation of some1's answer.
var file = DriveApp.getFileById(fileid);
DriveApp.getFolderById(folderid).addFile(file);
DriveApp.getRootFolder().removeFile(file);
Hope it helps!
There is no direct method in the File or Folder Classes to move files from one folder in Google Drive to another. As you mentioned you can copy the file to another folder with the method makeCopy() and then delete it with setTrashed(), the code should look like this:
var targetFolder = DriveApp.getFolderById(TARGET_FOLDER_ID);
var newDoc = DocumentApp.create(requestID + " - " + requestSummary); // Creates the Document in the user's Drive root folder
// Modify the new document here, example:
// var body = newDoc.getBody();
// body.appendParagraph("A paragraph.");
// newDoc.saveAndClose();
var driveFile = DriveApp.getFileById(newDoc.getId()); // Gets the drive File
driveFile.makeCopy(newDoc.getName(), targetFolder); // Create a copy of the newDoc in the shared folder
driveFile.setTrashed(true); // sets the file in the trash of the user's Drive
EDIT:
In a second thought and taking into account Ruben's comments. I agree that it is a better practice to implement Amit's answer.
It looks like there is now a moveTo() function with the Drive API (advanced services) that makes it easy to move files:
moveTo(destination)
Moves this item to the provided destination folder.
The current user must be the owner of the file or have at least edit
access to the item's current parent folder in order to move the item
to the destination folder.
Here is some code I used to move all files from the "screenshot input" folder to the "screenshot processed" folder:
var inputFolder = DriveApp.getFolderById(SCREENSHOT_INPUT_FOLDER_ID);
var processedFolder = DriveApp.getFolderById(SCREENSHOT_PROCESSED_FOLDER_ID);
var files = inputFolder.getFiles();
while (files.hasNext()) {
var file = files.next();
file.moveTo(processedFolder);
}
A bit safer approach compared to the previous ones:
If you remove link to the file first, then you will not be able to addFile.
If file is already located in the target folder, then the approach provided by Amit (https://stackoverflow.com/a/38810986/11912486) only removes file.
So, I suggest to use the following approach:
function move_file(file_id, target_folder_id) {
var source_file = DriveApp.getFileById(file_id);
var source_folder = source_file.getParents().next();
if (source_folder.getId() != target_folder_id) {
DriveApp.getFolderById(target_folder_id).addFile(source_file);
source_folder.removeFile(source_file);
}
}
can be improved by:
javascript camel style
multiple locations validation
Use File.moveTo(destination).
var newFileId = newDoc.getId();
var newFile = DriveApp.getFileById(newFileId);
newFile.moveTo(targetFolder);
Try this:
var file = DriveApp.getFileById(newDoc.getId());
targetFolder.addFile(file);
//DriveApp.getFolderById('root').removeFile(file); // remove from root
This question has been answered, but here is a slightly different configuration:
function moveFile(parameterObject) {
var currentFolderID,file,fileToMoveID,sourceFolder,targetFolder,targetFolderID;
fileToMoveID = parameterObject.fileToMoveID;
currentFolderID = parameterObject.currentFolderID;
targetFolderID = parameterObject.targetFolderID;
file = DriveApp.getFileById(fileToMoveID);//Get the file to move
if (!file) {
functionToHandleThisKindOfThing("there is no file");
return;
}
if (currentFolderID) {//The folder ID holding the current file was passed in
sourceFolder = DriveApp.getFolderById(currentFolderID);
} else {//No ID for the current folder
sourceFolder = file.getParents();
if (sourceFolder) {
if (sourceFolder.hasNext()) {
sourceFolder = sourceFolder.next();
}
}
}
targetFolder = DriveApp.getFolderById(targetFolderID);
targetFolder.addFile(file);
sourceFolder.removeFile(file);
}
function testCode() {
var o;
o = {
'fileToMoveID':"File ID of file to Move",
"targetFolderID":"ID of folder to Move to"
}
moveFile(o);
}
The script transfers all your personal files to a shared disk (Team drive). Saves the folder structure.
DRIVE_FOLDER_ID = '111aaa'; // Folder ID on the shared drive
function start() {
var files = DriveApp.searchFiles('"me" in owners');
while (files.hasNext()) {
var file = files.next();
newPath = fileMoveWithPath(file, DRIVE_FOLDER_ID);
console.info("New path: ", getFullPath(newPath));
}
}
function fileMoveWithPath(file, root) {
var folders = [],
parent = file.getParents();
// Проходим по иерархии папок текущего файла до корня
while (parent.hasNext()) {
parent = parent.next();
folders.push(parent);
parent = parent.getParents();
}
console.info("Old path: ", getFullPath(file));
if (folders.length > 0)
targetPath = makeNewPath(folders, DriveApp.getFolderById(root));
else
targetPath = DriveApp.getFolderById(root);
if (targetPath) {
targetFile = file.moveTo(targetPath);
return targetFile;
};
return;
}
function makeNewPath(folders, newroot) {
var f = folders.pop();
var query = "'" + newroot.getId() + "' in parents and title = '" + f.getName() + "' and mimeType='application/vnd.google-apps.folder' "
var targetFolder = DriveApp.searchFolders(query);
if (targetFolder.hasNext())
targetFolder = targetFolder.next()
else
targetFolder = newroot.createFolder(f.getName());
if (folders.length > 0)
return makeNewPath(folders, targetFolder)
else
return targetFolder;
}
function getFullPath(file) {
var folders = [],
parent = file.getParents();
while (parent.hasNext()) {
parent = parent.next();
folders.push(parent.getName());
parent = parent.getParents();
}
if (folders.length) {
return '> /' + folders.reverse().join("/") + '/' + file.getName();
}
return '> /' + file.getName();
}