Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check if a file exists with vbscript

Tags:

vbscript

I have a folder with many files. It looks like this file1.txt, newFile1.txt, file2.txt, newFile2.txt, file3.txt, newFile3.txt, file4.txt, newFile4.txt, ....

I have a code that generates the newFilei.txt . I want to write a vbscript that checks if a newFile exists in this folder or not. I tried this

Set objFolder = FSO.GetFolder("C:\myFolder\")

For Each objFile In objFolder.Files 
        fileName=objFile.name 
    If instr(fileName,"newFile*") =1 Then
        WScript.Echo "new File exist"
    End If
Next 

but this didnt work. any ideas ?

like image 511
KJohn Avatar asked Mar 13 '14 18:03

KJohn


People also ask

How do you create a file in VBScript?

Step 1: Press Ctrl + Shift + S on the keyboard, Or click File>Save As on the notepad window, this will open up a Save As dialog window asking where to save the current notepad document. Step 2: Now write any file name of your choice for this notepad document but make sure you write . vbs as its extension.

What is VB scripting language?

VBScript ("Microsoft Visual Basic Scripting Edition") is an Active Scripting language developed by Microsoft that is modeled on Visual Basic. It allows Microsoft Windows system administrators to generate powerful tools for managing computers with error handling, subroutines, and other advanced programming constructs.


1 Answers

Edit: The COM object made this very simple.

Dim FSO
Set FSO = CreateObject("Scripting.FileSystemObject")

If fso.FileExists("C:\myFolder\newFile.txt") Then
    'Perform Code
End If

Or, if you wanted your code to work

Set FSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = FSO.GetFolder("C:\myFolder\")
For Each objFile In objFolder.Files 
        fileName=objFile.name 
    If instr(fileName,"newFile") Then
        WScript.Echo "new File found"
    End If
Next 


And, pulling it all together.
Set FSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = FSO.GetFolder("C:\myFolder\")
Set objFiles = objFolder.Files 
For i=0 to objFiles.Count
    If FSO.FileExists("C:\myFolder\newFile" & i & ".txt") Then
        WScript.Echo "new File found"
    End If
Next 
like image 90
Rich Avatar answered Oct 15 '22 17:10

Rich