Skip to content

Instantly share code, notes, and snippets.

@KenjiOhtsuka
Last active May 5, 2024 00:25
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save KenjiOhtsuka/d4432b6d80ad2b81ab7c965de2a8a00d to your computer and use it in GitHub Desktop.
Save KenjiOhtsuka/d4432b6d80ad2b81ab7c965de2a8a00d to your computer and use it in GitHub Desktop.
Google Apps Script to Copy Folder Recursively
/**
This is a code of Google Apps Script for copying google drive folder content to other folder.
## Which situation the code resolve.
Google doesn't allow to move folder content to other folder which is managed by
other organization according to the policy of the GSUITE organization.
And, Google doesn't allow to change the content owner to the user in other
organizations.
For example, XXXXX@gmail.com can not move the folder to
shared folder managed by a GSUITE organization.
And, XXXXX@gmail.com can not change owner to the user in
a GSUITE user.
Even in such situation, a user can read the folder content so the user can
copy the content.
This script copies the folder to other folder recursively,
even if the destination folder is accessible and managed by other GSUITE
organization.
## Why it is created.
There is a webpage to copy a folder recursively but
the user in a GSUITE organization is sometimes prohibited
to use the script managed by others.
*/
function myFunction() {
// put source folder ID.
const fromFolder = DriveApp.getFolderById('1234567ABCDEFGHIJKLMNOPQRSTUVWXYZ')
// put destination folder ID.
const toFolder = DriveApp.getFolderById('1234567abcdefghijklmnopqrstuvwxyz')
// copy the folder content recursively.
copy(fromFolder, toFolder)
}
function copy(fromFolder, toFolder) {
// copy files
var files = fromFolder.getFiles()
while (files.hasNext()) {
var file = files.next();
var newFile = file.makeCopy(toFolder)
newFile.setName(file.getName())
}
// copy folders
var folders = fromFolder.getFolders()
while (folders.hasNext()) {
var folder = folders.next()
var newFolder = toFolder.createFolder(folder.getName())
copy(folder, newFolder)
}
}
@ozanerturk
Copy link

Good work!

@henriquebastos
Copy link

Life savior! Many thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment