How to Check if a File does NOT exist and display one overall response using a For Loop - vbscript

I'm trying to write a VBScript that will check whether a file exists in a folder or not based on a partial number. If anything in the folder has this number in the string it can continue, if not an error needs to display saying it's not in the system. I've gotten a code that lets me know that the file DOES exist, but I can't get a NOT version to work. Any ideas?
Dim FSO, str1, fileName
str1 = "001234"
Set FSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = FSO.GetFolder("C:\Users\GDoe\Desktop\FolderA\")
For Each objFile In objFolder.Files
fileName = objFile.Name
If InStr(fileName, str1) Then
MsgBox("Proceed")
Exit For
End If
Next

Unfortunately the FileSystemObject's FileExists method does not support wildcards, so the straightforward approach is not possible here.
The code you posted in your question is basically how one would check for the existence of a file with a partial name with VBScript and the FileSystemObject. You can modify that code into a check for the absence of a file with some minor changes. Define a variable before the loop and set it to False, then instead of displaying a message box set that vriable to True when you find a matching file:
fileFound = False
For Each objFile In objFolder.Files
fileName = objFile.Name
If InStr(fileName, str1) Then
fileFound = True
Exit For
End If
Next
If fileFound Then
MsgBox("Proceed")
Else
MsgBox("File doesn't exist.")
End If
Alternatively, you could shell out and check the exit code of the dir command:
Function FileExists(path, namepart)
Set sh = CreateObject("WScript.Shell")
rc = sh.Run("cmd /c dir ""*" & path & "\" & namepart & "*""", 0, True)
FileExists = Not CBool(rc)
End Function
dir returns 0 if it finds matching file(s) and 1 if it doesn't. CBool() converts the integer return code into a boolean value (0 → False, 1 → True). The negation then corrects the logic from "false if found" to "true if found".
Of course you could also name the function FileMissing and remove the negation, so that the function returns True if no matching file is found. That's just a matter of what logic works best in your code.
Note that you need to run the command with cmd /c, because dir is a cmd.exe builtin command, not an executable.

I actually just found a way to answer my own question but if there's a better way I'd also love to know.
Dim FSO, str1, fileName
str1 = "-001239"
Set FSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = FSO.GetFolder("C:\Users\GDoe\Desktop\FolderA\")
For Each objFile In objFolder.Files
fileName=objFile.Name
If InStr(fileName, str1) Then
MsgBox("Proceed")
Exit For
End If
Next
If InStr(fileName, str1) = 0 Then
MsgBox("File doesn't Exist")
End If
I took the rule that if string2 is not found in an InStr command it returns 0. Setting the result = 0 shows if I don't have the file.

Related

Process file If FileExists And 2nd FileExists

`Ok, I was asked to be more specific in my question. I have an undetermined number of files in my folder, for example:
NV_A1_mainx.dxf
NV_A1_resx.dxf
NV_B1_mainx.dxf
NV_B1_motx.dxf
NV_B1_motlx.dxf
The folder is Looped processing each file based on the InStr "mainx”, “motx”, or “resx”. On “motx” type files I want the script to search and see if there additional matching type file “motlx”. If there is it will process one way. If not it will process a second way. The filenames will be different however the filename convention will always have two underscores “_” followed by the InStr characters I search on.
Using the files above as an example, I wish to write a statement so that when NV_A1_motx.dxf is about to be processed it will check to see if there is a matching NV_B1_motlx.dxf in the folder.
The problem is the last line of my script. How do I write that statement correctly for "motx" to see if there is also a "motlx" file present in the folder?
Thx... hope that clarifies better my intentions.
Set App = CreateObject("Illustrator.Application")
Set FSO = CreateObject("Scripting.FileSystemObject")
Set SourceFolder = FSO.GetFolder("S:\SOCAL\Section_13\Road DXFs")
Set DXFfile = SourceFolder.Files
Set DXFfolder = FSO.GetFolder(SourceFolder)
Dim FileRef
For Each FileRef In SourceFolder.Files
If Instr(FileRef,"motx") > 0 then
Call Motx(FileRef)
ElseIf Instr(FileRef,"mainx") > 0 then
Call Mainx(FileRef)
ElseIf Instr(FileRef,"resx") > 0 then
Call Resx(FileRef)
Else
Msgbox "File is not being found or some issue with script."
End If
Next
Sub Motx(FileRef)
If ((App.Documents.Count > 0) And (FileExists("S:\SOCAL\Section_13\Road DXFs\SOCAL_B2_motlx.dxf"))) Then
Else
Thank you for your input Jose. I was getting errors plugging the code in so what I did was just strip the code to the basics to see if your code would find the matching files. What I did was in the folder have just two files:
NV_B2_motlx.dvx and
NV_B2_motx.dvx
Testing with your script as so:
Set App = CreateObject("Illustrator.Application")
Set FSO = CreateObject("Scripting.FileSystemObject")
Set SourceFolder = FSO.GetFolder("S:\SOCAL\Section_13\Road DXFs")
Set DXFfile = SourceFolder.Files
Set DXFfolder = FSO.GetFolder(SourceFolder)
For Each FileRef In SourceFolder.Files
' default property of `FileRef` object is `Path`
If Instr( FileRef.Name, "motx", vbTextCompare) > 0 Then
I f fso.FileExists( fso.BuildPath( fso.GetParentFolderName( objFile.Path), _
Replace( FileRef.Name, "motx", "motlx", 1, -1, vbTextCompare))) Then
'motlx' exists
MsgBox "We have a match!"
Else
'motlx' does not exist
MsgBox "Sorry, no match"
End If
End If
Next
Running this I got the following error message: Type mismatch:'[string:"NV_B2_motlx.dxf"]' Code 800A000D Line 9 Char 5.
Maybe this code stub could help:
Dim FileRef
For Each FileRef In SourceFolder.Files
' default proprty of `FileRef` object is `Path`
If Instr( FileRef.Name, "motx", vbTextCompare) > 0 Then
If fso.FileExists( fso.BuildPath( fso.GetParentFolderName( objFile.Path), _
Replace( FileRef.Name, "motx", "motlx", 1, -1, vbTextCompare))) Then
'motlx' exists
Else
'motlx' does not exist
End If
Reference:
Functions (VBScript): InStr, Replace
FileSystemObject Properties: .Name, .Path
FileSystemObject Methods: .BuildPath, .GetParentFolderName

If FileExists delete another file

I am trying to add a sub-routine to a VBScript. In short, I am trying to see if one type of file exists, it will delete another file.
There will be files like:
SOCAL_CU59_res.dxf
SOCAL_CU59_main.dxf
SOCAL_CU59_mot.dxf
SOCAL_CU59_motl.dxf
but on occassion there may be a file with an "x" at the end of the filename:
SOCAL_CU59_resx.dxf
SOCAL_CU59_mainx.dxf
SOCAL_CU59_motx.dxf
SOCAL_CU59_motlx.dxf
They would all be in the same folder. The "x" file has priority. So if it exist I want to delete the matching file file without the "x".
Here is what I have so far but errors. The check filesize routine I added works great but it's after that I am having no luck:
Dim oFSO, sDirectoryPath, oFOLDER, oFile
Set oFSO = CreateObject("Scripting.FileSystemObject")
sDirectoryPath = "S:\SOCAL\Section_11\Road DXFs\"
RecurseFolders sDirectoryPath
Sub RecurseFolders(sFolder)
'Here we set the oFolder object, note that its variable scope is within
'this sub, so you can set it many times and it's value will only be
'that of the sub that's currently running.
Set oFolder = oFSO.GetFolder(sFolder)
'Here we are looping through every file in the directory path.
For Each oFile In oFolder.Files
'This just checks for a file size less than 100Kb
If oFile.Size <= 1085 And Right(LCase(oFile.Name),3) = "dxf" Then
oFile.Delete True
End If
Next
For Each oFile In oFolder.Files
'This checks if there is a file with an 'x' at the end of filename
If FileExists (Right(oFile.Name),1) = "x" Then
oFile.Delete True
End If
Next
'Here we do the recursive bit. We need to loop through each folder in
'the directory too and call the same sub to ensure we check every folder
'in the path.
For Each oFolder In oFolder.SubFolders
RecurseFolders oFolder.Path
Next
End Sub
The script creates both files, but does not delete the file that does NOT have the "x". The error says for line 204, Char 5:
Wrong number of arguments or invalid property assignment: 'Right'
The line the error refers to is: If FileExists (Right(oFile.Name),1) = "x" Then.
You have a few inherent problems that you need to correct in order to do this properly. First, you need to make the parenthesis correction mentioned by Ansgar Wiechers. Second, you should remove the duplicate loop. There's no need to loop over all of the files multiple times. Finally, you should store the files to be deleted until after the loop has finished. Deleting a file while it is in the file set that is currently being looped over could produce unexpected results or unexplained errors.
With that said, here's how I would approach this. You'll note all of the corrections I've mentioned.
Dim oFSO, sDirectoryPath, oFOLDER, oFile
Set oFSO = CreateObject("Scripting.FileSystemObject")
sDirectoryPath = "S:\SOCAL\Section_11\Road DXFs\"
Dim arrFilesToDelete() 'an empty dynamic array to hold files to be deleted later
Dim i = 0 'an iterator used to track the array pointer
RecurseFolders sDirectoryPath
DeleteExtraFiles arrFilesToDelete
Sub RecurseFolders(sFolder)
'Here we set the oFolder object, note that its variable scope is within
'this sub, so you can set it many times and it's value will only be
'that of the sub that's currently running.
Set oFolder = oFSO.GetFolder(sFolder)
'Here we are looping through every file in the directory path.
For Each oFile In oFolder.Files
'Is the file a "dxf" file
If LCase(Right(oFile.Name)) = "dxf" Then
'This just checks for a file size less than 100Kb
If oFile.Size <= 1085 And Right(LCase(oFile.Name),3) = "dxf" Then
End If
'This checks if there is an 'x' at the end of filename
If LCase(Right(oFile.Name) 5) = "x.dxf" Then
'if so, store its counterpart for deletion later
sBadFile = Replace(oFile.Name, "x.dxf", ".dxf")
ReDim Preserve arrFilesToDelete(i)
arrFilesToDelete(i) = oFile.Path & "\" & sBadFile
i = i + 1
End If
End If
Next
'Here we do the recursive bit. We need to loop through each folder in
'the directory too and call the same sub to ensure we check every folder
'in the path.
For Each oFolder In oFolder.SubFolders
RecurseFolders oFolder.Path
Next
End Sub
Sub DeleteExtraFiles(arrFiles)
For Each sFile in arrFiles
If oFSO.FileExists(sFile) Then
oFSO.DeleteFile sFile
End If
Next
End Sub
You put the inner closing parenthesis in the wrong place. The parameter 1 belongs to the function Right. Change this:
If FileExists (Right(oFile.Name),1) = "x" Then
into this:
If FileExists (Right(oFile.Name,1)) = "x" Then
With that said, there might be other issues with that line. VBScript doesn't have a built-in function FileExists and your code snippet doesn't reveal if that function is implemented elsewhere in your code, so whether passing it a character and comparing its return value to the character x actually makes sense is hard to say.
If you meant to use the FileSystemObject method FileExists you'd need to call it from the actual FileSystemObject instance:
If oFSO.FileExists(...) Then
and pass it a filename or path, not a single character or a boolean value.
If you want to test if for any given file foo.ext another file foox.ext exists, and in that case delete foo.ext you'd do something like this:
For Each oFile In oFolder.Files
xFilename = oFSO.GetBaseName(oFile) & "x." & oFSO.GetExtensionName(oFile)
If oFSO.FileExists(oFSO.BuildPath(oFile.Parent, xFilename)) Then
oFile.Delete True
End If
Next

VBScript Renaming File Code Issue

I wrote a simple vbscript to rename files in a particular folder. Specifically to remove particular content from the filname.
The Script I wrote (listed below) runs fine but the highlighted part (second IF-THEN statement) doesn't run. I can't figure out whats wrong with the code. I plan to add more IF-THEN statement to remove particular content from file names.
I'm a novice at this so please be patient with me. Can anyone help?
Set objFS = CreateObject("Scripting.FileSystemObject")
strFolder="C:\Users\Admin2\Downloads\Compressed"
Set objFolder = objFS.GetFolder(strFolder)
For Each strFile In objFolder.Files
strFileName = strFile.Name
If InStr(strFileName,"(2014)") > 0 Then
strNewFileName = Replace(strFileName,"(2014)","")
strFile.Name = strNewFileName
End If
**If InStr(strFileName,"(digital)") > 0 Then
strNewFileName = Replace(strFileName,"(digital)","")
strFile.Name = strNewFileName
End If**
Next
Type prefix fraud detected:
For Each strFile In objFolder.Files
"strFile" should be "objFile". Dangerous extra variable in:
strFileName = strFile.Name
The variable "strFileName" will get stale if you change "objFile.Name". Use a variable to hold the new/desired name instead.
strNewFileName = objFile.Name
Renaming the file twice will loose changes on the way. Modify "strNewFileName" (in steps or all at once:
strNewFileName = Replace(Replace(strNewFileName, "(2014)", ""), "(digital)", "")
; you don't really need the If guard, because Replace won't change strings that don't contain the target).
Check for .FileExists(strNewFileName) before you do the rename.
Can you prove that there are file names that contain "(digita1)" <-- mark the digit 1) exactly? Lower vs. upper case? A nasty blank?
I hope the following code helps
Set objFS = CreateObject("Scripting.FileSystemObject")
strFolder="pathtofolder"
Set objFolder = objFS.GetFolder(strFolder)
For Each objFile In objFolder.Files
ObjFileName = ObjFile.Name
NewFileName = Replace(Replace(ObjFileName,"(2014)",""),"(digital)","")
Set fileSystemObject = CreateObject("Scripting.FileSystemObject")
If fileSystemObject.FileExists(NewFileName) Then
Else
ObjFile.Name = Trim(NewFileName)
End If
Next

How to Copy a file that was read from a list

Hello guys I have an issue or issues with my code above
I'm trying to get "sExtension" to be search in a different folder other that the one I'm using to save my script since this script will be use as a Startup Script on many computers
(It works only if I run the script in the same folder "sExtension", "ExtAssign.txt" and sComputername are otherwise it wont find the path)
This is what it should do
Read a file called "ExtAssign.txt" (There is a full list of computer names in that file) and if it find the computer name on that file then it should copy a file with the with the extension number assigned to that computer name from a file server to "C:\" Drive
For this example I'm trying to do this locally, If I can make it then I'll try it from my File Server
Set objFSO = CreateObject("Scripting.FileSystemObject")
set oFso = CreateObject("Scripting.FileSystemObject")
Set objFS = CreateObject("Scripting.FileSystemObject")
Set fso = CreateObject("Scripting.FileSystemObject")
set oShell = WScript.CreateObject("WScript.Shell")
set oShellEnv = oShell.Environment("Process")
Set folder = Fso.GetFolder("C:\Users\XXXXX\Desktop\Test\Extensions\")
Set wshshell = CreateObject("WScript.Shell")
Set objNetwork = CreateObject("WScript.Network")
Set ObjEnv = WshShell.Environment("Process")
Set objFso = WScript.CreateObject("Scripting.FileSystemObject")
Scomputername = ObjEnv("COMPUTERNAME")
Set objFSO = CreateObject("Scripting.FileSystemObject")
set objWShell = wScript.createObject("WScript.Shell")
Dim strFile
'File to scan
strFile = "C:\Users\XXXXX\Desktop\Test\Extensions\Extassign\ExtAssign.txt"
Dim strPattern
'Look for computer name in file
strPattern = scomputername
Set objFso = WScript.CreateObject("Scripting.FileSystemObject")
Set objFile = objFS.OpenTextFile(strFile)
Do Until objFile.AtEndOfStream
Dim strLine
'Read each line and store it in strLine
strLine = objFile.ReadLine
'If the line matches the computer name, save the line to ExtArray
If InStr(strLine,strPattern)>0 Then
Dim ExtArray
'Split the line and separate the extension
ExtArray = Split(strLine,"|", -1, 1)
Dim sExtension
'Save the extension to sExtension
sExtension=ExtArray(1)
End If
Loop
'If the sExtension is empty, computer was not found, send message and terminate script.
If sExtension="" Then
WScript.Echo "ERROR: Computer "& scomputername &" not found in Extension Assignment List, so no extension has been set. Avaya will not be launched. Please contact your IT department for assistance."
Else
'If the sExtension contains a number, Copy that file to C:\ and rename it to Config.xml
fso.CopyFile "C:\Users\XXXXX\Desktop\Test\Extensions\ "& sExtension &"", "C:\Config.xml", True
End If
at the end it if it finds the file sExtension it will rename it to Config.xml but it wont do it unless I run the script in the same folder sExtension and sComputername.
I get File not found error
Thank you in advance and Happy new year!
The culprit is most likely this line:
fso.CopyFile "C:\Users\XXXXX\Desktop\Test\Extensions\ "& sExtension &"", "C:\Config.xml", True
There is a trailing space after the last backslash in the path, so you're creating a path
C:\Users\XXXXX\Desktop\Test\Extensions\ 12345
^
when you actually want a path
C:\Users\XXXXX\Desktop\Test\Extensions\12345
On a more general note: why are you creating 7(!) FileSystemObject instances (replacing one of them three times on top of that)? And 3(!) WScript.Shell instances? You don't even use most of them, not to mention that you don't need the Shell object in the first place. You only use it for determining the computer name, which could be done just fine using the WScript.Network object (that you don't use at all).
Also, please don't ever use comments like this:
'Read each line and store it in strLine
strLine = objFile.ReadLine
It's quite obvious that you read each line and assign it to the variable strLine. Comments shouldn't rephrase what you're doing (the code already does that, at least when you're using speaking variable and function names), but why you're doing it, i.e. what the purpose of a particular code section is.
Your code could be reduced to something as simple as this:
Set fso = CreateObject("Scripting.FileSystemObject")
Set net = CreateObject("WScript.Network")
computername = net.ComputerName
foldername = "C:\Users\XXXXX\Desktop\Test\Extensions"
filename = fso.BuildPath(foldername, "Extassign\ExtAssign.txt")
Set f = fso.OpenTextFile(filename)
Do Until f.AtEndOfStream
line = f.ReadLine
If InStr(line, computername) > 0 Then
arr = Split(line, "|", -1, 1)
If UBound(arr) >= 1 Then extension = arr(1)
End If
Loop
f.Close
If IsEmpty(extension) Then
WScript.Echo "ERROR: Computer "& computername &" not found in ..."
Else
fso.CopyFile fso.BuildPath(foldername, extension), "C:\Config.xml", True
End If

checking format to a text box

I need a method to check the contents of the text entered to make sure they are correctly entering a folder path. So it needs to be in the format of:
Drive Letter :\ Folder
e.g. C:\My Documents
If they haven't typed in that format I need to stop and show a message telling them to double check.
I have tried the Filter function but I haven't quite got it to work. Any help would be awesome. I don't have any code to show because I am nto sure where to start.
I also tried the common dialog, but the user jsut needs the type the path, not select the file. All I want to check is if the text type is within that format DRIVE:\FOLDER, that is it. So if the type "BLAH" in the text bax a message says Hey you type a correct path.
In VB6, to test whether your text contains a valid folder:
If Len(Dir("c:\My Documents", vbDirectory))>0 Then
'it's a folder
End If
Have you thought of implemeting the common dialog control to allow the selection of a correct folder instead - it'll be much more likely to be accurate.
Some example code of folder browsing from here:
Private Sub Command1_Click()
On Error Resume Next
Const WINDOW_HANDLE = 0
Const NO_OPTIONS = 0
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.BrowseForFolder(WINDOW_HANDLE, "select folder:", NO_OPTIONS, "C:Scripts")
Set objFolderItem = objFolder.Self
objPath = objFolderItem.Path
objPath = Replace(objPath, "", "\")
Print objPath
End Sub
Alternatively you could validate the folder first you could check for ":\" using eith instr or mid
then you could validate the folder and even include an option to create it if not present with the filesystemobject (needs a reference set) here it is in function form, you can pass the contents of the textbox for validation.
Function DirExists(pFile As String, Optional pCreate As Boolean = False)
'
Dim fso As New FileSystemObject
Dim vPath As Variant
Dim sPath As String
Dim y As Variant
DirExists = False
If fso.FolderExists(pFile) Then
DirExists = True
Else
If pCreate Then
vPath = Split(pFile, "\")
For Each y In vPath
sPath = sPath & y & "\"
If Not fso.FolderExists(sPath) Then
fso.CreateFolder (sPath)
If fso.FolderExists(pFile) Then
DirExists = True
Exit Function
End If
End If
Next
End If
End If
End Function

Resources