Google Apps Script is a powerful scripting language that allows you to automate tasks in Google Suite applications. It can help you perform tasks using APIs and create custom files, applications, and workflows with the help of a few lines of code. In this post, we will discuss how to move a file into a folder with Google Apps Script.
Moving Files into Folders
Google Drive provides a simple way to move files in and out of folders. Let’s assume you have a Google Sheet file and want to move it from one folder to another. The code to move a file between folders is quite simple.
function moveFiles() {
var fileId = 'FILE_ID_TO_MOVE',
folderId = 'FOLDER_ID_TO_MOVE_TO';
var file = DriveApp.getFileById(fileId);
var folder = DriveApp.getFolderById(folderId);
folder.addFile(file);
}
The fileId and folderId should be replaced by the actual IDs of the file and the folder respectively. To move the file, we first get the file by its ID using the DriveApp.getFileById() method. Similarly, we get the folder by its ID using the DriveApp.getFolderById() method. Finally, we use the folder.addFile(file) method to add the file to the folder. This moves the file to the specified folder.
Let’s take a look at another example. Suppose you want to move all the files in a folder called ‘source’ to a folder called ‘destination’. You can accomplish this using the following code.
function moveAllFiles() {
var sourceFolder = DriveApp.getFolderByName("source");
var destinationFolder = DriveApp.getFolderByName("destination");
var files = sourceFolder.getFiles();
while (files.hasNext()) {
var file = files.next();
destinationFolder.addFile(file);
sourceFolder.removeFile(file);
}
}
In this code, we first get the sourceFolder and destinationFolder by their names using the DriveApp.getFolderByName() method. Next, we get all the files in the sourceFolder using the getFiles() method. We then loop through all the files using the while loop and use the destinationFolder.addFile(file) method to move each file to the destination folder. Finally, we use the sourceFolder.removeFile(file) method to remove the file from the source folder.