Skip to content

Instantly share code, notes, and snippets.

@tvst
Last active October 21, 2022 22:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tvst/1833e973d13aa59d67f956416e4783f6 to your computer and use it in GitHub Desktop.
Save tvst/1833e973d13aa59d67f956416e4783f6 to your computer and use it in GitHub Desktop.
Move folder to Shared Drive (AppsScript)
const FOLDER_ID_TO_MOVE = 'FOLDER ID GOES HERE'
const DESTINATION_FOLDER_ID = 'FOLDER ID GOES HERE'
function main() {
const folderToMove = DriveApp.getFolderById(FOLDER_ID_TO_MOVE)
const newParentFolder = DriveApp.getFolderById(DESTINATION_FOLDER_ID)
moveFolder(folderToMove, newParentFolder)
}
function moveFolder(folderToMove, newParentFolder) {
// Create destination folder (or reuse if one with same name exists)
const folderName = folderToMove.getName()
const existingFoldersWithThisName = newParentFolder.getFoldersByName(folderName)
const newFolder = existingFoldersWithThisName.hasNext()
? existingFoldersWithThisName.next()
: newParentFolder.createFolder(folderToMove.getName())
// Move all child files
const oldChildFiles = folderToMove.getFiles()
while (oldChildFiles.hasNext()) {
const childFile = oldChildFiles.next()
childFile.moveTo(newFolder)
}
// Recurse through all child folders
const oldChildFolders = folderToMove.getFolders()
while (oldChildFolders.hasNext()) {
const childFolder = oldChildFolders.next()
moveFolder(childFolder, newFolder)
}
// Delete original folder (now empty)
folderToMove.setTrashed(true)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment