I try to move a file from my root-folder into a defined folder. But my script send me the fautl: "Exception: The parameters (String) don't match the method signature for DriveApp.File.moveTo." - but why?
Does anyone has a tip for me?
function myMoveFile() {
var myFolderID = DriveApp.searchFolders("Title Contains 'Final_Folder'").next().getId();
var myNewDoc = DocumentApp.create("Doc per Script");
var myFileID = myNewDoc.getId();
DocumentApp.openById(myFileID).getBody().appendParagraph("TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT");
Logger.log(myFolderID);
DriveApp.getFileById(myFileID).moveTo(myFolderID);
}
Thanks
destination of moveTo(destination) is the folder object which is not the folder ID. I thought that this might be the reason for your issue. So how about the following modification?
Modified script:
function myMoveFile() {
var myFolder = DriveApp.searchFolders("Title Contains 'Final_Folder'").next();
var myNewDoc = DocumentApp.create("Doc per Script");
var myFileID = myNewDoc.getId();
DocumentApp.openById(myFileID).getBody().appendParagraph("TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT");
Logger.log(myFolder.getId());
DriveApp.getFileById(myFileID).moveTo(myFolder);
}
Reference:
moveTo(destination)
Added:
About the following 2nd question,
My intention is to create a file via GScript and then move it to a defined folder (e.g. "Final_Folder"). There are 2 folders with the same name that I want to move I avoid that the file is moved to the wrong folder.
In this case, as a workaround, how about using the star? At Google Drive, a star can be added to the files and folders. In your situation, when the same folders are existing and you want to move the file to one of those folders, please add a star to the specific folder you want to use. I thought that this might be a workaround for identifying the specific folder from the same folder name.
Sample script:
Before you run this script, please add a star to the folder you want to use. And, run this script. By this, the file is moved to the starred folder. By this, you can use the specific folder from the same folder names.
function myMoveFile() {
var folders = DriveApp.searchFolders("Title Contains 'Final_Folder'");
while (folders.hasNext()) {
var myFolder = folders.next();
if (myFolder.isStarred()) {
var myNewDoc = DocumentApp.create("Doc per Script");
var myFileID = myNewDoc.getId();
DocumentApp.openById(myFileID).getBody().appendParagraph("TEXT TEXT TEXT TEXT TEXT TEXT TEXT TEXT");
Logger.log(myFolder.getId());
DriveApp.getFileById(myFileID).moveTo(myFolder);
break;
}
}
}
Related
I am looking for a code that will help me to find the hyperlink of another google sheet on my google drive, everything i have read explains how to get the link for the active sheet..
any ideas?
Thanks a lot
You need to use DriveApp with functions getFilesByName or getFilesByType. Then provide file id to SpreadsheetApp.openById.
This look will give you the hyperlink to every sheet in a spreadsheet
SpreadsheetApp.openById(file.getId()).getSheets().forEach(s =>
tree.txt.push([ `=HYPERLINK("https://docs.google.com/spreadsheets/d/${file.getId()}/edit#gid=${s.getSheetId()}","${s.getName()}")`]));
It generates a column. It's just a fragment of a piece of code
I have something a bit more simple to apply. The code below goes into the Drive folder and list down every file (doc/sheets/pdf etc) and its hyperlink.
All you will need to change is your tab name to store the folder details and your Gdrive folder ID.
If you want to extract folders within a folder in the future you can switch getFiles() to getFolders().
function folderitems(){
const ss=SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet 1'); //Edit tab name to list the folder details
const parentFolder=DriveApp.getFolderById('INPUT FOLDER ID HERE'); //Input Gdrive ID here
const contents=parentFolder.getFiles();
ss.appendRow(['name','link']);
while (contents.hasNext()){
var file = contents.next();
var name=file.getName();
var link=file.getUrl();
ss.appendRow([name,link]);
}
}
Outcome should look something like this.
To retrieve the URL of one spreadsheet by script
function getFileUrl() {
var nameOfFile = 'your file name'
var files = DriveApp.getFilesByName(nameOfFile);
while (files.hasNext()) {
var file = files.next();
console.log (file.getUrl())
}
}
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 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);
}
Starting with 'google apps script'. I've created a simple script that logs some information with 'Logger.log("message");' with this lines being in a loop, so the log message is quite large.
I'd like now to create an html file with that same information and either being able to download that file locally or have it downloaded to my google drive.
Any idea how that could be achieved? I've tried looking examples for a while but I cannot have anything working...
Many thanks!
Yes you can, you should read first. Have a look this documentation
function createMyHTMLlog()
{
var folders = DriveApp.getFoldersByName('ff');// ff:your folder name on drive
if (folders.hasNext())
{
var folder = folders.next(); //select the folder
folder.createFile('Log','<b> your message here </b>', MimeType.HTML); //create the file
}
}
Update: Add more content later
function logUpdate()
{
var children = folder.getFilesByName('Log');// log is the created file name
if (children.hasNext())
{
var file = children.next();
var logContent = file.getAs('text/plain').getDataAsString();// get available msg
logContent = logContent.concat('<br>your<b> updated message </b> here'); // combine with new msg
file.setContent(logContent);
}
}
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.