Skip to content

Instantly share code, notes, and snippets.

@nagarindkx
Last active May 31, 2021 08:21
Show Gist options
  • Save nagarindkx/e2897455b2ede2ae168f8cd5ccf16982 to your computer and use it in GitHub Desktop.
Save nagarindkx/e2897455b2ede2ae168f8cd5ccf16982 to your computer and use it in GitHub Desktop.
Copy File and Subfolder from My Drive folder to Shared Drives
function copyFilesFromDriveToShareDrive() {
/*
Created by: Kanakorn Horsiritham
Digital Innovation and Data Analytics (DIDA)
Faculty of Medicine
Prince of Songkla University
Hatyai, Songkhla
THAILAND
*/
sourceID='GoogleDrive-Folder-ID'
destinationID='SharedDrives-Folder-ID'
copyFolder(sourceID, destinationID)
//moveFolder(sourceID, destinationID)
}
function copyFolder(sourceID, destinationID){
sFD = DriveApp.getFolderById(sourceID)
dFD = DriveApp.getFolderById(destinationID)
files = sFD.getFiles()
while(files.hasNext()) {
f=files.next()
if (! dFD.getFilesByName(f.getName()).hasNext()) {
f.makeCopy(f.getName(), dFD)
console.log('copy file: ' + f.getName())
} else {
Logger.log( "file: " + f.getName() + ' exist')
}
}
folders=sFD.getFolders()
nextlevel=[]
while(folders.hasNext()) {
fd = folders.next()
tmpDestinationFolder = dFD.getFoldersByName(fd.getName())
if (! tmpDestinationFolder.hasNext()) {
new_folder = dFD.createFolder(fd.getName())
Logger.log( "create folder: " + fd.getName())
} else {
new_folder = tmpDestinationFolder.next()
Logger.log( "folder: " + fd.getName() + ' exist')
}
nextlevel.push([fd.getId(), new_folder.getId()])
}
nextlevel.forEach(function(r){
copyFolder(r[0], r[1])
})
}
function moveFolder(sourceID, destinationID){
sFD = DriveApp.getFolderById(sourceID)
dFD = DriveApp.getFolderById(destinationID)
files = sFD.getFiles()
while(files.hasNext()) {
f=files.next()
if (! dFD.getFilesByName(f.getName()).hasNext()) {
console.log('file: ' + f.getName())
f.moveTo( dFD)
console.log('move file: ' + f.getName())
} else {
Logger.log( "file: " + f.getName() + ' exist')
}
}
folders=sFD.getFolders()
nextlevel=[]
c=0
if (folders.hasNext()) {
while(folders.hasNext()) {
fd = folders.next()
tmpDestinationFolder = dFD.getFoldersByName(fd.getName())
if (! tmpDestinationFolder.hasNext()) {
new_folder = dFD.createFolder(fd.getName())
} else {
new_folder = tmpDestinationFolder.next()
Logger.log( "folder: " + fd.getName() + ' exist')
}
nextlevel.push([fd.getId(), new_folder.getId()])
c=c+1
}
nextlevel.forEach(function(r){
moveFolder(r[0], r[1])
})
} else {
sFD.setTrashed(true)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment