• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

Tachytelic.net

  • Get in Touch
  • About Me

Function to check if a file exists in VBScript

October 11, 2017 by Paulie Leave a Comment

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

Now that you know how to check for a file in VBScript, read up on how to check if a file exists with Powershell.

If you found this post helpful, I’d really appreciate it if you left a rating.

Filed Under: How To Tagged With: VBScript

Reader Interactions

Leave a Reply Cancel reply

Primary Sidebar

Link to my LinkedIn Profile
Buy me a coffee

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 245 other subscribers.

Go to mobile version