Move folder matching a specific name into another folder? - google-apps-script

Could someone provide me with a simple example how to use App Script to move a folder matching a specific name (not ID) into another folder inside Google Drive?
I have searched the existing threads but couldn't find anything specific to matching a specific folder name.

I believe your goal as follows.
You want to move a folder to other folder in your Google Drive using Google Apps Script.
For this, how about this answer? In your case, when the parent folder of the folder is moved, all files and sub folders in the folder can be moved. So the script can be simpler than the script for copying files. This has already been mentioned by Cooper's comment.
The sample script is as follows. As the input values, the source folder name and destination folder ID are used.
Sample script:
In this sample script, Drive service is used.
function myFunction() {
const sourceFolderName = "###"; // Please set the source folder name.
const destinationFolderId = "###"; // Please set the destination folder ID.
const src = DriveApp.getFoldersByName(sourceFolderName);
if (src.hasNext()) {
const srcFol = src.next();
srcFol.getParents().next().removeFolder(srcFol);
DriveApp.getFolderById(destinationFolderId).addFolder(srcFol);
}
}
Note:
When Drive API is used, the script becomes as follows.
function myFunction() {
const sourceFolderName = "###"; // Please set the source folder name.
const destinationFolderId = "###"; // Please set the destination folder ID.
const src = DriveApp.getFoldersByName(sourceFolderName);
if (src.hasNext()) {
Drive.Files.patch({parents: [{id: destinationFolderId}]}, src.next().getId());
}
}
References:
removeFolder(child)
addFolder(child)

Related

Update Google Doc Files With Data Pulled From a SpreadSheet Using Doc File Name

I need to assign a membership number to each request I receive from aspiring members of my association.
Aspiring members fill a Google Docs file. When their requests are validated, those files need to be updated with the assigned membership number.
Inside the spreadsheet I have two columns. One contains the membership number and the other contains the ID of the request.
Spreadsheet Screenshot
The doc files are named with the ID of the request as well. The membership numbers should be added in place of the placeholder {membershipnumber} found in the doc files.
Doc File Screenshot
Is anyone able to help?
Thanks a lot for your precious help!
I really have no idea how to accomplish this.
I believe your goal is as follows.
You have Google Document files in the specific folder and have a Google Spreadsheet including the values for updating the Google Document files.
You want to replace the value of {membershipnumber} with the values of column "A" by searching the filename using the value of column "C".
In this case, how about the following sample script?
Sample script:
In this sample, please copy and paste the following script to the script editor of Google Spreadsheet and set the variables. And, save the script.
function myFunction() {
const folderId = "###"; // Please set your folder ID of the folder including the Google Document files.
const sheetName = "Sheet1"; // Please set your sheet name.
const folder = DriveApp.getFolderById(folderId);
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
const obj = sheet.getRange("A2:C" + sheet.getLastRow()).getDisplayValues().reduce((o, [a, , c]) => (o[c] = a.trim(), o), {});
const docs = folder.getFilesByType(MimeType.GOOGLE_DOCS);
while (docs.hasNext()) {
const file = docs.next();
const filename = file.getName().trim();
if (obj[filename]) {
const doc = DocumentApp.openById(file.getId());
doc.getBody().replaceText("{membershipnumber}", obj[filename]);
}
}
}
When this script is run, the Google Document files are updated using the values of column "A" by searching the Document files with the filename retrieved from column "C".
References:
reduce()
getFilesByType(mimeType)
replaceText(searchPattern, replacement)

Appscript to get hyperlink to another google sheet

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())
}
}

google apps script. copy files to one drive

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()

Script to save full Google Spreadsheet to folder

I want to create a function to save a spreadsheet to a folder.
I'm almost there, I think I just need to adjust the synthax of the createFile class.
Here is my code:
const spreadsheet2 = SpreadsheetApp.getActiveSpreadsheet();
var folder2 = DriveApp.getFoldersById("my_folder_id").next();
var filename2 = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange("B97").getValue();
folder2.createFile([I think here is my missing command].setName(filename2));
Could someone finish it?
You want to copy the active Spreadsheet to the specific folder.
You want to use the filename from getActiveSheet().getRange("B97").getValue().
You want to achieve this using Google Apps Script.
If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.
Modification points:
At DriveApp.getFoldersById("my_folder_id").next(), there is no method of getFoldersById. When you want to use the folder ID, please use DriveApp.getFolderById(folderId).
Unfortunately, the Spreadsheet cannot be directly created with createFile(). In your case, in order to copy the active Spreadsheet, you can use makeCopy().
When above points are reflected to your script, it becomes as follows.
Modified script:
var folderId = "###"; // Please set the folder ID you want to put the copied Spreadsheet.
const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var filename2 = spreadsheet.getActiveSheet().getRange("B97").getValue();
var folder = DriveApp.getFolderById(folderId);
DriveApp.getFileById(spreadsheet.getId()).makeCopy(filename2, folder);
References:
getFolderById()
makeCopy()

Download file to google drive folder using app script

I am using this script to download a URL set in a google sheet cell to a specific folder in google drive called "game_thumb"
If cell B1 is "yyyyy.com/picture.png" I expect picture.png to be downloaded to the google drive folder.
I get an error"ReferenceError: "DocsList" not defined. (line 5).
I also would like the file to be renamed to include Cell A1
(contentCellA1_picture.png) before it is downloaded to drive.
The code I use:
function getFile(fileURL) {
// see https://developers.google.com/apps-script/class_urlfetchapp
var response = UrlFetchApp.fetch(fileURL);
var fileBlob = response.getBlob()
var folder = DocsList.getFolder('game_thumb');
var result = folder.createFile(fileBlob);
debugger; // Stop to observe if in debugger
}
You want to save the downloaded file in the specific folder which has the name of game_thumb.
You want to set the value of cell "A1" to the filename of downloaded file.
If my understanding is correct, how about this modification?
For your question 1:
From your question, it is found that although I'm not sure whether the data is the file blob you want, the data from the URL can be retrieved. So in order to remove the error, please modify as follows.
From:
var folder = DocsList.getFolder('game_thumb');
To:
var folder = DriveApp.getFoldersByName('game_thumb').next();
In this modification, it supposes that the folder which has the name of game_thumb is only one in your Drive. If there are the folders with several same names, please tell me.
For your question 2:
Please modify as follows.
From:
var result = folder.createFile(fileBlob);
To:
var name = SpreadsheetApp.getActiveSheet().getRange("A1").getValue();
var result = folder.createFile(fileBlob).setName(name);
From your question, I'm not sure whether you are using the container-bound script or standalone script, and also I'm not sure where sheet there is the cell "A1" is. So this modification supposes that the cell "A1" of the active sheet is used.
References:
getFoldersByName()
getValue()
If I misunderstood your question and this modification didn't work, I apologize. At that time, can you provide the information of the situation?