समझिए
Folder या file लेना
सबसे सुरक्षित तरीका ID है — URL से copy करें: drive.google.com/drive/folders/<FOLDER_ID>।
const folder = DriveApp.getFolderById('FOLDER_ID');
const file = DriveApp.getFileById('FILE_ID');
Drive में नाम unique नहीं होते (दो folders का नाम एक हो सकता है), इसलिए नाम से खोजने पर iterator मिलता है:
const it = DriveApp.getFoldersByName('Invoices');
while (it.hasNext()) {
const f = it.next();
console.log(f.getName(), f.getId(), f.getUrl());
}
Folder लो, न हो तो बनाओ
यह helper कई projects में काम आएगा:
function getOrCreateFolder(parent, name) {
const it = parent.getFoldersByName(name);
return it.hasNext() ? it.next() : parent.createFolder(name);
}
उदाहरण: invoices को साल और महीने के हिसाब से रखना:
function monthFolder(date) {
const root = DriveApp.getFolderById('INVOICES_ROOT_ID');
const tz = Session.getScriptTimeZone();
const year = getOrCreateFolder(root, Utilities.formatDate(date, tz, 'yyyy'));
return getOrCreateFolder(year, Utilities.formatDate(date, tz, 'MM-MMM')); // e.g. 10-Oct
}
Files बनाना और move करना
// A text/CSV file
const folder = monthFolder(new Date());
const csv = 'Item,Qty\nRing,2\nChain,1';
const file = folder.createFile('stock.csv', csv, MimeType.CSV);
// Move an existing file
DriveApp.getFileById('FILE_ID').moveTo(folder);
// Make a copy in another folder
DriveApp.getFileById('FILE_ID').makeCopy('Copy of report', folder);
Files की list शीट में
function listFolder() {
const folder = DriveApp.getFolderById('FOLDER_ID');
const files = folder.getFiles();
const out = [['Name', 'Type', 'Size (KB)', 'Last updated', 'Link']];
while (files.hasNext()) {
const f = files.next();
out.push([
f.getName(),
f.getMimeType(),
Math.round(f.getSize() / 1024),
f.getLastUpdated(),
f.getUrl()
]);
}
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Files');
sheet.clearContents();
sheet.getRange(1, 1, out.length, out[0].length).setValues(out);
}
Queries से खोजना
searchFiles Drive की search syntax इस्तेमाल करता है:
const pdfs = DriveApp.searchFiles(
"mimeType = 'application/pdf' and modifiedDate > '2026-10-01T00:00:00' and title contains 'Invoice'"
);
Sharing (सावधानी से)
file.addViewer('customer@example.com'); // share with one person
// file.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW); // anyone with link
Invoices या customer data के लिए "anyone with the link" से सावधान रहें — जहाँ हो सके, ख़ास लोगों के साथ ही share करें।
मुख्य बातें
- जहाँ हो सके ID इस्तेमाल करें; नाम unique नहीं होते, इसलिए iterator मिलता है।
getOrCreateFolderduplicate folders बनने से रोकता है।moveTo,makeCopy,createFileसे ज़्यादातर व्यवस्थित करने के काम हो जाते हैं।