I am trying to figure out a way to check whether or not a set of folders I'm looping through has a file (google docs file) in it. If it does have a file in the folder (there's ever only one file) I would like to make a copy of it.
I'm not sure how to access that file and use the makeCopy() method since I don't know the name / ID of the file in the folder.
Any help would be very appreciated.
How about following sample script? THis sample retrieves files in the folderId. If there is a file in the folder, the file is copied. From your question, it is found that there is only one file in the folder. So in this script, the one file is copied.
Sample script :
var folderId = "### folder ID ###";
var folder = DriveApp.getFolderById(folderId);
var files = folder.getFiles();
var file = [];
while (files.hasNext()) {
file.push(files.next());
}
if (file.length > 0){
file[0].makeCopy();
}
Other sample script :
Since the file which is copied is only one, follwing sample script can be also used for your situation. This may be more simple than above.
var folderId = "### folder ID ###";
var files = DriveApp.getFolderById(folderId).getFiles();
files.hasNext() && files.next().makeCopy();
If you want to use folder name and the folder name is only one in your Drive, please use following script.
var folderName = "### folder name ###";
var files = DriveApp.getFoldersByName(folderName).next().getFiles();
files.hasNext() && files.next().makeCopy();
You have the ID of the folders (or at least you have their names so you can get their IDs using files.list?q=name="foo"
Once you have the folder IDs, you can look for any files therein using files.list?q="folderID" in parents
Related
I am trying to write a google apps script to clear a given folder given the folder ID but the function is not behaving as expected. It runs without an error but it seems isTrashed() does not delete all files? I have looked at the documentation but can't seem to figure out how to get all the files in a folder to be deleted.
function clearFolder(folderId) {
// Get the folder
var folder = DriveApp.getFolderById(folderId);
Logger.log("clearFolder on folder: %s",folder.getName())
// Get all the files in the folder
var files = folder.getFiles();
// Iterate through the files and delete them
while (files.hasNext()) {
var file = files.next();
Logger.log("clearFolder deleting file named '%s'",file.getName())
file.isTrashed();
}
}
The file.isTrashed() method does not delete files. It determines whether the file is in the trash, and returns a true/false value that is ignored by the code you quote.
To delete files, use file.setTrashed(true).
I would have files stored in google drive and I would like to copy (or move) those files to my OneDrive. I have managed to connect OneDrive to google drive and I can successfully create folders and upload files by file ID. I am trying to copy (or move) multiple files at once from google drive to OneDrive though without any luck yet. I am not good at programming just doing everything by tutorials only but yet could not find any working one. Maybe anyone could guide me how to do it? For the final idea I would like to achieve that files from google drive would be copied even to separate folders by the part of file title (name and surname, if to be exact). Currently I have "developed" such script:
function moveFiles(source, dest_folder) {
var source = DriveApp.getFolderById("1faFbaXJNziwIGyer2H2IPALQ8ahBfGMc");
var prop = PropertiesService.getScriptProperties();
var odapp = OnedriveApp.init(prop);
var files = DriveApp.getFiles();
while (files.hasNext()) {
var file = files.next();
var dest_folder =
OnedriveApp.init(PropertiesService.getScriptProperties()).uploadFile(files,
"/samplefolder");
}
}
I believe your current situation and your goal are as follows.
You are using OnedriveApp.
You have already been finished the authorization process. So you have already been had the access token and refresh token in the PropertiesServices.
You want to upload the files in a specific folder of Google Drive to a specific folder in OneDrive.
The number of files is 10 - 20.
The file size is small.
From your following reply
I have changed accordingly to: var files = file.getId(); but then I receive such error: TypeError: Cannot read property 'getId' of undefined moveFiles # srcpt.gs:5 If I use DriveApp.getFiles() or source.getFiles(), I receive such error: Exception: Unexpected error while getting the method or property getFileById on object DriveApp. convToMicrosoft # code.gs:629 OnedriveApp.uploadFile # code.gs:460 Appreciated for any help.
About var files = file.getId(); and If I use DriveApp.getFiles() or source.getFiles(), I receive such error:, unfortunately, I cannot understand it.
In this case, how about the following modification?
Modified script:
function myFunction() {
var prop = PropertiesService.getScriptProperties();
var odapp = OnedriveApp.init(prop);
var source = DriveApp.getFolderById("###"); // Please put your folder ID.
var files = source.getFiles();
while (files.hasNext()) {
var file = files.next();
odapp.uploadFile(file.getId(), "/samplefolder/"); // Please set the destination folder name. In this case, the folder name in OneDrive.
}
}
When "/samplefolder" is used, an error occurs. Please enclose the folder name by / like "/samplefolder/". Please be careful about this.
When this script is run, the files in the specific folder of Google Drive are copied to the destination folder of /samplefolder/ in OneDrive.
References:
OnedriveApp
getFolderById(id)
getFiles()
I need a way to open a spreadsheet only by having the name of the corresponding file and the folder where the file is located. What I'm trying to do is creating a temporary copy of an active spreadsheet and reading information from the copy file rather than the active one. But unfortunately this copy file won't have a constant ID and URL as it's going to be erased every time after the script is done, and re-created with the next running of the script.
What I already tried is using the URL of the temporary file in order to open the spreadsheet itself, as you can see below.
But it's not useful for me, as I don't have a constant URL of this file (as it will be erased in the end of the script and have a new URL with the next script). But I have a constant name of the file, as well as this will be the only file in the respective folder.
What I also tried is looking for methods to open file only using its name (which is "temp_copy" in a 'temp_folder'). But I didn't find a working solution.
var report = SpreadsheetApp.getActiveSpreadsheet();
var temp_folder =
DriveApp.getFolderById("1EAsvVcFjIw5iGTeF_SxxQJLVlaLHl_pR");
DriveApp.getFileById(report.getId()).makeCopy("temp_copy", temp_folder);
var temp_copy = SpreadsheetApp.openByUrl(' ');
var hiddenSheet = temp_copy.getSheetByName('DATE');
var lastRow = hiddenSheet.getSheetValues(1,1,1,1);
var sheet = temp_copy.getSheetByName('forCSV');
var lastColumn = sheet.getLastColumn();
var activeRange = sheet.getRange(1,2,lastRow,lastColumn);
What I'm expecting as a result is to make the link between the 3rd line of the code (when making a copy of the basic file) and 5th line of the code onwards (when referencing specific range from the temporary file) only by using name of the file or respective folder. In theory it seems so easy, I should be missing something somewhere...
Many thanks in advance!
You can use DriveApp to get a FileIterator which contains the Sheet.
var file, files = DriveApp.getFilesByName("temp_copy");
if (files.hasNext ()){
file = files.next(); // Get first result for name
} else {
return "";
}
var sheet = SpreadsheetApp.openById(file.getId())
So I've been trying to write a script, which is doing that with partial success.
The problem is that this script is misbehaving for unknown reasons(to me).
Currently, it copies(or adds) the files from the source to the destination folder. Then it converts the newly added file from CSV to GS and finally deleted the copied CSV.
The problem is that when it deletes the copied CSV it deletes it from both the source and the destination folders, and I want to delete it just from the destination folder.
Finally, I end up with only the converted csv(now GS) in both folders and what I want to achieve is simply to keep the original file in the original folder in its original format and have the google sheet in the destination folder.
Can somebody please help me?
Here's what I have :
function copyFilesToFolder (latestFileIdString, folderId) {
var file = DriveApp.getFileById(latestFileIdString);
DriveApp.getFolderById(folderId).addFile(file);
convertToGS(folderId)
}
function convertToGS(folderId) {
var folder = DriveApp.getFolderById(folderId);
var files = folder.getFiles();
while (files.hasNext()) {
var file = files.next();
Drive.Files.copy({}, file.getId(), {convert: true});//convert CSV to SS
Drive.Files.remove(file.getId());//remove CSV
//appendNewToDashboardSS(folderId);
}
}
How about this modification?
Modification points :
addFile() is used for adding a parent to a file. By this, the file has 2 parents. This means that one file ID has 2 folder IDs. So when one file of 2 folders is removed, both files are removed.
When it copies a file, please use makeCopy().
Modified part :
From :
DriveApp.getFolderById(folderId).addFile(file);
To :
file.makeCopy(DriveApp.getFolderById(folderId));
If I misunderstand your question, I'm sorry.
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.