RideDeadHorses
RideDeadHorses

Reputation: 13

for each loop: how to step out of conditions

I am stuck at creating a loop for testing filenames with VBScript. To be precise, I am trying to perform something like a jump in a For Each loop. The loop should test all files in a folder and in some cases it should delete some files.

But while running, it deletes a file and tries to test the deleted file against the next condition. So I look for a solution to end this check and jump to the next file but I am not able to find a working solution.

for each file in folder.files
  if (filename = "foo.bar") then
    log.writeline("found foo.bar -> delete!")
    fs.deletefile (folder & file.name), true
    'exit for
  end if
  if (isNumeric(firstPosition)) then
    if (isNumeric(secondPosition)) then
      log.writeline("2 numbers seen -> alright!")
    else
      log.writeline("Filename is corrupt!")
      fs.copyFile file, errorFolder, true
      fs.deleteFile file, true
      'exit for 
    end if
  end if

Upvotes: 1

Views: 140

Answers (1)

JosefZ
JosefZ

Reputation: 30123

Use else as follows:

for each file in folder.files
  if (filename = "foo.bar") then
    log.writeline("found foo.bar -> delete!")
    fs.deletefile (folder & file.name), true
    'exit for
  else
    if (isNumeric(firstPosition)) then
      if (isNumeric(secondPosition)) then
        log.writeline("2 numbers seen -> alright!")
      else
        log.writeline("Filename is corrupt!")
        fs.copyFile file, errorFolder, true
        fs.deleteFile file, true
        'exit for 
      end if
    else
    end if
  end if
next

or even elseif as follows

for each file in folder.files
  if (filename = "foo.bar") then
    log.writeline("found foo.bar -> delete!")
    fs.deletefile (folder & file.name), true
    'exit for
  elseif (isNumeric(firstPosition)) then
    if (isNumeric(secondPosition)) then
      log.writeline("2 numbers seen -> alright!")
    else
      log.writeline("Filename is corrupt!")
      fs.copyFile file, errorFolder, true
      fs.deleteFile file, true
      'exit for 
    end if
  else
  end if
next

There is no goto-like statement in VBScript; there are structured control mechanisms only. Read VBScript User's Guide and VBScript Language Reference

Upvotes: 2

Related Questions