问题
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 ?
回答1:
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
来源:https://stackoverflow.com/questions/22387719/how-to-check-if-a-file-exists-with-vbscript