Created
December 19, 2022 08:26
-
-
Save Tushar-N/0872309a95524817f8e71496c002deeb to your computer and use it in GitHub Desktop.
Google apps script to copy folders in Google Drive
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function getDriveFolderFromPath (path) { | |
return (path || "/").split("/").reduce ( function(prev,current) { | |
if (prev && current) { | |
var fldrs = prev.getFoldersByName(current); | |
return fldrs.hasNext() ? fldrs.next() : null; | |
} | |
else { | |
return current ? null : prev; | |
} | |
},DriveApp.getRootFolder()); | |
} | |
function getSharedFolder(name){ | |
EMAIL = '[email protected]' | |
var folders = DriveApp.searchFolders('sharedWithMe'); | |
while (folders.hasNext()) { | |
var folder = folders.next(); | |
if (folder.getName() == name && folder.getOwner().getEmail() == EMAIL){ | |
console.log(folder.getName(), folder.getId()); | |
} | |
} | |
return folder | |
} | |
function copyFolder(source, target) { | |
console.log('Running:', source.getName()) | |
var folders = source.getFolders(); | |
var files = source.getFiles(); | |
while (files.hasNext()) { | |
var file = files.next(); | |
file.makeCopy(file.getName(), target); | |
} | |
while (folders.hasNext()) { | |
var subFolder = folders.next(); | |
var folderName = subFolder.getName(); | |
var targetFolder = target.createFolder(folderName); | |
copyFolder(subFolder, targetFolder); | |
} | |
} | |
function run() { | |
SRC_PATH = "path/to/src" | |
TARGET_PATH = "path/to/dst" | |
// If source folder is a shared folder: | |
// var source = getSharedFolder(SRC_PATH) | |
var source = getDriveFolderFromPath(SRC_PATH) | |
var target = getDriveFolderFromPath(TARGET_PATH) | |
console.log(source.getName(), target.getName()) | |
copyFolder(source, target); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment