Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

VBScript Error handling

Status
Not open for further replies.

vgwprja

Programmer
Mar 27, 2008
24
0
0
US
I have never used error handling before and wonder where to put the 'error monitoring'. Here is a script that I use:

'VB Script - Archive Outbound FTP Files (pgp format)

Dim filesys, file, folderName, objFile, folderObj, fileColl, objRegExp, newFile
Set filesys = CreateObject("Scripting.FileSystemObject")

folderName = "e:\ftpdata\toreliance\"
Set folderObj = filesys.GetFolder(folderName)
Set fileColl = folderObj.Files

Set objRegExp = New RegExp
objRegExp.Pattern = ".asc" 'looking for files with = ".asc" extension
objRegExp.IgnoreCase = True

'archive files
For Each objFile In fileColl
If objRegExp.Test(objFile.Name) Then
filesys.MoveFile objFile, folderName & "archive\" & newFile
End If
Next

I assume that an error could occur in the 'For Each' loop. There could be a case that there are no files to archive and that is OK and should not generate an error. An error could be that the 'archive' folder has been deleted or changed as an example. So where should I put the error monitoring? Within the 'For Each' or right after?

This is what I had in mind:

If Err.Number <> 0 Then
Err.Clear
On Error GoTo 0
'here I plan to write to a log file
Wscript.Quit
End If

Thank you.
 
Well you put it wherever you think the error will occur. So for your code if you thought the movefile might fail for some reason then you would do this:

'VB Script - Archive Outbound FTP Files (pgp format)

Dim filesys, file, folderName, objFile, folderObj, fileColl, objRegExp, newFile
Set filesys = CreateObject("Scripting.FileSystemObject")

folderName = "e:\ftpdata\toreliance\"
Set folderObj = filesys.GetFolder(folderName)
Set fileColl = folderObj.Files

Set objRegExp = New RegExp
objRegExp.Pattern = ".asc" 'looking for files with = ".asc" extension
objRegExp.IgnoreCase = True

'archive files
For Each objFile In fileColl
If objRegExp.Test(objFile.Name) Then
[red]On Error Resume Next [/red]
filesys.MoveFile objFile, folderName & "archive\" & newFile
[red]If Err.Number <> 0 Then
logFile.WriteLine "Move file failed: " & Err.Number & ") - " & Err.Description
Err.Clear
End If
On Error Goto 0 [/red]
End If
Next

[red]"... isn't sanity really just a one trick pony anyway?! I mean, all you get is one trick, rational thinking, but when you are good and crazy, oooh, oooh, oooh, the sky is the limit!" - The Tick[/red]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top