我有一个Google App脚本,它将文件从一个文件夹复制到另一个文件夹。首先,它检查源文件夹中是否有任何文件。如果有,则删除目标文件夹中的文件,然后将文件从源文件夹复制到目标文件夹。复制完成后,应删除源文件夹中的文件。但是,它没有像我期望的那样工作,我相信问题出在if
else
声明中。我在while
if
语句中有一个else
循环。我的想法是while
循环在检查if
语句之前完成,但似乎并非如此。
问题是脚本会删除目标文件夹中的文件,而不是保留这两个文件。 (我现在只有2个文件)。
这是我的代码:
while(sourceFolders.hasNext()){
var sourceFolder = sourceFolders.next();
var sourceFiles = sourceFolder.getFiles();
// Check to see if there are new files to copy
if(sourceFiles.hasNext()){
//++ If so, delete the files in the target folder
deleteTheFiles(TARGET_FOLDER);
//++ Copy new files to target folder
while(sourceFiles.hasNext()){
var sourceFile = sourceFiles.next();
var sourceFileName = sourceFile.getName();
sourceFile.makeCopy(sourceFileName, TARGET_FOLDER);
//++ Delete files in source folder
sourceFile.setTrashed(true);
}
//-- If not, do nothing
} else {
Logger.log('There are not files at this time.')
}
}
答案 0 :(得分:0)
因为源代码中有多个文件夹,所以第一个while
循环不止一次迭代,从而触发deleteTheFiles()
函数,该函数删除了放入目标的第一个文件夹。我在counter
循环之外创建了一个简单的while
变量,解决了这个问题。这是代码:
function copyFilesToBackup() {
var sourceFolders = SOURCE_FOLDER.getFolders();
var counter = 0; // <-- ADDED THIS COUNTER -->
while(sourceFolders.hasNext()){ // <-- HERE IS THE PROBLEM
var sourceFolder = sourceFolders.next();
var sourceFiles = sourceFolder.getFiles();
// Check to see if there are new files to copy
if(sourceFiles.hasNext()){
//++ If so, delete the files in the target folder
if(counter < 1){ <-- SINCE WE ONLY NEED TO DELETE THE TARGET ONCE -->
deleteTheFiles(TARGET_FOLDER);
counter++; <-- INCREMENT COUNTER -->
}
//++ Copy new files to target folder
while(sourceFiles.hasNext()){
var sourceFile = sourceFiles.next();
var sourceFileName = sourceFile.getName();
sourceFile.makeCopy(sourceFileName, TARGET_FOLDER);
//++ Delete files in source folder
sourceFile.setTrashed(true);
}
//-- If not, do nothing
} else {
Logger.log('There are not files at this time.')
}
}
}