// Drive · Apps Script

Fix "Cannot retrieve the next object: iterator has reached the end" in Apps Script.

The "iterator has reached the end" error in Apps Script almost always means the Drive iterator returned zero results — usually because getFilesByName matches exact names, not substrings. Learn to gate next() behind hasNext() and switch to searchFiles() for partial-match queries.

I'm calling getFilesByName() or getFoldersByName() and my script crashes with "Cannot retrieve the next object: iterator has reached the end" even though I know the file exists.

The script

copy · paste · trigger
find-file-safe.gs
Apps Script
// Safe Drive file lookup — gates next() behind hasNext(),
// falls back to partial-match search when exact lookup finds nothing.
function findFileByPartialName(partialName) {
  var exact = DriveApp.getFilesByName(partialName);
  if (exact.hasNext()) {
    return exact.next();
  }

  // Exact match found nothing; try a title-contains search.
  var query = 'title contains "' + partialName + ='" and trashed = false';
  var results = DriveApp.searchFiles(query);
  if (results.hasNext()) {
    return results.next();
  }

  throw new Error('No file found matching: ' + partialName);
}

function run() {
  var file = findFileByPartialName('Q4 Report');
  Logger.log(file.getName() + ' — ' + file.getId());
}

Need a variant? Gnaw writes a custom version from one sentence — fields, triggers, edge cases handled.

Walkthrough

Why the iterator is exhausted before you call next()

The error fires at the moment you call next() on a FileIterator or FolderIterator that has no more items to yield. The Drive API does not return null — it throws. So if your iterator was already empty (zero results), the very first next() call crashes.

The most common reason the iterator is empty: you passed a partial name to getFilesByName(). That method does a strict equality match on the file title. A file named "Q4 Report Final.xlsx" will not appear in getFilesByName('Q4 Report'). The iterator comes back empty, you skip the hasNext() guard because you assumed the file exists, and the crash follows immediately.

I hit this the first time I was automating a folder of monthly invoices whose names all included a shared prefix. The files were plainly visible in Drive; the script crashed every run. The fix took two minutes once I understood the method is exact-match only.

Gate every next() call behind hasNext()

The mechanical fix is always the same: call hasNext() before next(), every time, on every iterator. The iterator interface in Apps Script follows the standard Java Iterator pattern — hasNext() returns a boolean, next() advances and returns the item.

For a single expected file the pattern is: check hasNext(), return the item if true, handle the miss if false. For collecting all matches, a while (iterator.hasNext()) loop is the right shape. Never assume a non-zero result count, even if you created the file yourself — it may be in the Trash, in a different account's Drive, or just misnamed.

Wrapping the lookup in a helper that throws a descriptive error (rather than the cryptic iterator message) pays off the first time a teammate runs your script and hits an edge case. 'No file found matching: Q4 Report' is actionable; 'Cannot retrieve the next object' is not.

Switch to searchFiles() when partial matching is the actual need

If you genuinely need substring or prefix matching, getFilesByName() is the wrong tool. Use DriveApp.searchFiles() with a Drive query string. The relevant operator is title contains "...", which matches any file whose title includes that substring, case-insensitively.

The query string follows the Drive Files.list API syntax. Common additions: trashed = false (exclude Trash), mimeType = 'application/vnd.google-apps.spreadsheet' (restrict to Sheets), and parents in 'FOLDER_ID' (scope to a specific folder). You can AND these clauses together in one string.

One real gotcha: title contains is a full-word token match in some Drive backends, not a true arbitrary-substring scan. For most practical names with spaces or distinct words it works reliably. If you need true substring matching on arbitrary character sequences, list the folder contents and filter in Apps Script with indexOf() — slower, but exact.

searchFiles() also returns a FileIterator, so the same hasNext() discipline applies.

Want a custom version?

Describe your sheet and the rule you want. Gnaw writes the Apps Script — fields, triggers, edge cases — in one shot.

FAQ

4 questions
Does hasNext() consume the first result?
No. hasNext() is a pure peek — it does not advance the iterator. You still call next() afterward to retrieve the item. Calling hasNext() multiple times without an intervening next() returns the same boolean each time.
Why does the error say 'iterator has reached the end' even when I can see the file in Drive?
Almost always an exact-name mismatch. Check the full file name including extension and any trailing spaces. Also confirm the file is not in the Trash (trashed files are excluded from getFilesByName by default) and that the script is running under an account that has at least read access to the file.
Can I use getFoldersByName() the same way, and does it have the same exact-match limitation?
Yes on both counts. getFoldersByName() is exact-match, returns a FolderIterator, and requires the same hasNext() gate. For partial folder matching, use DriveApp.searchFolders() with a title contains query.
What if I need to find a file inside a specific folder, not all of Drive?
Get the folder first with DriveApp.getFolderById('FOLDER_ID'), then call folder.getFilesByName() or folder.searchFiles() on the returned Folder object. The same exact-match vs. contains distinction applies at the folder scope.