if then endive, another smart solution instead of if then

advertisements

I have the following VB script How to write this VB script with case syntax? In order to perform professional writing in place if then…. yael

Set fso = CreateObject("Scripting.FileSystemObject") 

If (fso.FileExists("C:\file1 ")) Then
    Verification=ok
Else
  WScript.Echo("file1")
  Wscript.Quit(100)
End If 

If (fso.FileExists("C:\file2 ")) Then
  Verification=ok
Else
  WScript.Echo("file2")
  Wscript.Quit(100)
End If 

If (fso.FileExists("C:\file3 ")) Then
    Verification=ok
Else
  WScript.Echo("file3")
  Wscript.Quit(100)
End If

. . . .


You can't use select/case for this type of thing, but there are other ways to condense or simplify the code.

First, reverse the test condition:

If Not (fso.FileExists("C:\file1 ")) Then
  WScript.Echo("file1")
  Wscript.Quit(100)
End If

This avoids needing a "do nothing" command after if/then.

Next, you can wrap things up in functions and subroutines to reduce the repetitive bulk of the code:

function TestFile(sFileName)
  TestFile = fso.FileExists(sFileName)
end function

sub ErrorExit(sMessage, nCode)
  WScript.Echo sMessage
  WScript.Quit nCode
end sub

Then your series of tests becomes:

if not TestFile("c:\file1") then
  ErrorExit "file1 not found", 100

elseif not TestFile("c:\file2") then
  ErrorExit "file2 not found", 100

elseif not TestFile("c:\file3") then
  ErrorExit "file3 not found", 100
end if