Function to check if a file exists in VBScript

It’s very easy to check if a file exists in VBScript, but to make this common task even easier it’s best to use a quick function to do the job. I’ve written two functions, one using the FilesystemObject and another using WMI, both of which return a Boolean.

VBScript Function to check if a file exists on the local computer

Function FileExists(FilePath)
  Set fso = CreateObject("Scripting.FileSystemObject")
  If fso.FileExists(FilePath) Then
    FileExists=CBool(1)
  Else
    FileExists=CBool(0)
  End If
End Function

To use the function just do something like the following:

If FileExists("c:\testfolder\testfile.txt") Then
  WScript.Echo "Does Exist"
Else
  WScript.Echo "Does not exist"
End If

This will work perfectly if you are only looking for files on your local machine. But what if you want to check if a file exists on a remote machine?

VBScript Function to check if a file exists on a remote machine

Function FileExists(FilePath, Computer)
  Set objWMIService = GetObject("winmgmts:\\" & Computer & "\root\cimv2")
  FilePath = Replace(FilePath, "\", "\\")
  Set Files = objWMIService.ExecQuery ("Select * From CIM_Datafile Where Name = '" & FilePath & "'")
  
  If Files.Count > 0 Then
      FileExists=CBool(1)
  Else
      FileExists=CBool(0)
  End If
End Function

Use the function like this:

If FileExists("c:\testfolder\testfile.txt", "testcomputer") Then
  WScript.Echo "Does Exist"
Else
  WScript.Echo "Does not exist"
End If

 

Leave a Reply

Your email address will not be published. Required fields are marked *