How we can access files and folders in the drive using Google app scripts?
I will explain with an example: Let’s create one Google Sheet and get all the file details stored in your drive on the Google Sheet, such as File name, File URL, File ID, owner, and size.
Now, go to the extensions and click on the Apps Script.
Which redirects to the Script Editor.
We are going to get the list of all the files and URLs on the Sheet, Now we create a function on the editor called Get All Files.
First, get the active spreadsheet and get the sheet by name. Next, we are going to hit the drive. We need to go to the services and you will get the Drive API. Click on drive API and add.
After Adding the drive services, we get all the files using a while loop.
Below is the function code with a screenshot
function get_all_files() {
var ss= SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('my_file');
var files = DriveApp.getFiles();
var final = [];
while (files.hasNext())
{
var one_file = files.next();
var name = one_file.getName();
var url = one_file.getUrl();
var id = one_file.getId();
var owner = one_file.getOwner();
var size = one_file.getSize();
var temp = [name,url,id,owner,size];
sheet.appendRow(temp);
}
sheet.getRange(2,1,final.length, final[0].length).setValues(final);
}
On every loop, it gets the temp and appends it to the sheet.
I will give another example. We will move the file from one folder to another in Google Drive.
Suppose you have two folders in your drive called folder1 and folder2 and you have one file in folder1 and you want to move that file from folder1 to folder2.
We can create a new function called transfer file on the script editor. In the function, we first get the IDs of the source folder, folder1, and the target folder, folder2. Then we get the folder using the [get folder by id] function. Now we get the file from the source folder. Last we move the file to the target folder using the moveTo function.
I am also sharing the function code and screenshots for more clarity.
function transfer_file(){
var source_folder_id = '1It_ny0x9d6FXU6q1k9luZAMq0ESbWzw_';
var target_folder_id = '1LPTxvgmhBY_zPoADjA80MoOcnxWOlyDn';
var source_folder = DriveApp.getFolderById(source_folder_id);
var target_folder = DriveApp.getFolderById(target_folder_id);
var source_files = source_folder.getFiles();
while (source_files.hasNext())
{
var this_file = source_files.next();
this_file.moveTo(target_folder);
}
}
Lastly, we select the function and run the selected function.
As a result, they moved the file from folder 1 to folder 2.
Leave a Reply