Last active
October 21, 2022 22:21
-
-
Save tvst/1833e973d13aa59d67f956416e4783f6 to your computer and use it in GitHub Desktop.
Move folder to Shared Drive (AppsScript)
This file contains hidden or 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
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