Faster method to copy file - vbscript

I am trying to copy file using following script.
Option Explicit
Const ForWriting = 2
Dim objFSO
Dim desfolder
Dim oShell
dim s
desfolder = "D:\Databases"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Recurse objFSO.GetFolder("D:\Databases\Images")
Sub Recurse(objFolder)
Dim objFile, objSubFolder
For Each objFile In objFolder.Files
If LCase(objFSO.GetExtensionName(objFile.Name)) = "tif" Then
s = Right(objFile.Name, 10)
S = Left(s, 1)
If Left(s, 1) = "C" Then
Set oShell = WScript.CreateObject("WScript.Shell")
oShell.Run "xcopy.exe " & objFile & " " & desfolder & " /R /Y", _
0, True
End If
End If
Next
For Each objSubFolder In objFolder.SubFolders
Recurse objSubFolder
Next
End Sub
What I am trying to do is checking files in folders and subfolders. If file is tif then checking weather it contains required letter "C" at specific position. and using xcopy to copy the file.
It works fine but is very slow.
Is there any faster method to do this?
Edit: What I want exactly is to find c*.tif in a folder and its subfolders.

Don't use xcopy then. Doing it your way spawns a new process each time you copy a file. Just use the file object's Copy method and be done with it.
Sub Recurse(objFolder)
Dim objFile, objSubFolder
For Each objFile In objFolder.Files
If LCase(objFSO.GetExtensionName(objFile)) = "tif" Then
If LCase(Left(objFile.Name, 1) = "c" Then
objFile.Copy desfolder & "\"
End If
End If
Next
For Each objSubFolder In objFolder.SubFolders
Recurse objSubFolder
Next
End Sub
Note that your destination path requires a trailing backslash because it's a folder (you'd get a "permission denied" error without it). Otherwise you need to specify the destination path including the filename, e.g. like this:
objFile.Copy objFSO.BuildPath(desfolder, objFile.Name)

Related

VBS - File Created But I Can't See It Or Open It

I was trying to build a VBS to test creating files because a larger script I wrote isn't creating an output file. The point of the following script is to test functionality; which I'm not currently seeing.
Option Explicit
Dim objFSO, objFSOText, objFolder, objFile
Dim strDirectory, strFile
strDirectory = "C:\Test\next"
strFile = "\Try.txt"
' Create the File System Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
' Create the Folder specified by strDirectory on line 10
Set objFolder = objFSO.CreateFolder(strDirectory)
' -- The heart of the create file script
'-----------------------
'Creates the file using the value of strFile on Line 11
' -----------------------------------------------
Set objFile = objFSO.CreateTextFile(strDirectory & strFile)
Wscript.Echo "Just created " & strDirectory & strFile
Wscript.Quit
While running this code, everything works the first time but there isn't an output file in the destination directory. When I run it again it throws an error that the file already exists.
I think the problem is that you are trying to create the path "C:\Test\next", which is a structure of two nested folders) in one go and also do not test if that path already exists.
To create a nested folder structure, I have added a small helper function CreateNestedFolder to your code and tidied it up a bit:
Option Explicit
Dim strDirectory, strFile, overwrite
strDirectory = "C:\Test\next"
strFile = "Try.txt"
overwrite = True 'set this to False if you do not wish to overwrite an existing file
'Create the (nested) Folder Structure specified by strDirectory if it does not exist yet
If Not CreateNestedFolder(strDirectory) Then
Wscript.Echo "Could not create folder " & strDirectory
Else
Dim objFSO, objFile
' Create the File System Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
' -- The heart of the create file script
'-----------------------
'Creates the file using the value of strFile
' -----------------------------------------------
'combine the directory and filename
strFile = strDirectory & "\" & strFile
'Create the new file and write something in it
Set objFile = objFSO.CreateTextFile(strFile, overwrite)
objFile.WriteLine("This is a test.")
objFile.Close
Wscript.Echo "Just created " & strFile
'Clean up the used objects
Set objFile = Nothing
Set objFSO = Nothing
End If
Function CreateNestedFolder(ByVal sPath)
'Helper function to create a nested folder structure.
'Returns True on success, False otherwise
Dim aFolders, oFso, i, firstIndex
On Error Resume Next
Set oFso = CreateObject("Scripting.FileSystemObject")
'Check if the path already exists
If Not oFso.FolderExists(sPath) Then
'Find the root drive and split the path in subfolder parts
aFolders = Split(sPath, "\")
'Get the root path from the complete path
If Left(sPath, 2) = "\\" Then
'If this is a UNC path then the root will be "\\server\share"
sPath = "\\" & aFolders(2) & "\" & aFolders(3)
firstIndex = 4
Else
'For a local path, the root is "X:"
aFolders = Split(sPath, "\")
sPath = aFolders(0)
firstIndex = 1
End If
'Loop through the aFolders array and create new folders if needed
For i = firstIndex to UBound(aFolders)
If Len(aFolders(i)) > 0 Then
sPath = sPath & "\" & aFolders(i)
If Not oFso.FolderExists(sPath) Then oFso.CreateFolder sPath
End If
Next
End If
CreateNestedFolder = (Err.Number = 0)
On Error GoTo 0
Set oFso = Nothing
End Function

For Each file doesn't go beyond 1000 files?

I'm trying to get a CSV output for a Blender render job duration estimation. I like to input file time stamps into an Excel, so I wrote below VBScript (it's not 100% ready, but the echo should work). However, it won't iterate beyond the 1000th png file. It ends at file 9999.
Currently I got 35432 png files.
Why won't VBScript go beyond 1000 files?
Option Explicit 'force all variables to be declared
Const ForWriting = 2
Dim objFSO
Set objFSO = CreateObject("Scripting.FileSystemObject")
Dim objTS 'Text Stream Object
Set objTS = objFSO.OpenTextFile("C:\tmp\output.txt", ForWriting, True)
Recurse objFSO.GetFolder("C:\tmp")
objTS.Close()
Sub Recurse(objFolder)
Dim objFile, objSubFolder
For Each objFile In objFolder.Files
If LCase(objFSO.GetExtensionName(objFile.Name)) = "png" Then
WScript.Echo objFSO.GetBaseName(objFile.Name) & vbTab & _
CDate(objFile.DateLastModified) & vbTab & _
CDate(objFile.DateCreated)
objTS.WriteLine(objfile.Path)
End If
Next
'unmark to make it recursive
'For Each objSubFolder In objFolder.SubFolders
' Recurse objSubFolder
'Next
End Sub

Memory leak with a recursive sub using VBScript

I'm creating a script that will allow a user to search within a specified directory with a search term. The script will create a CSV file and then write the base file name, the file size, the last modified date, and the absolute path of files that contain the search term within the file name. However, I'm running into an issue searching subfolders within the folder. The issue is that I'm running out of memory within the subroutine.
Here is the script I've written thus far.
Dim fileCount, searchPath, searchTerm, CheckFile, wholePath
Dim objFSO, objFolder, objFile, objWriteFile
Dim savePath
objCheckFile = "C:\Users\USERFILE\Desktop\Audit.csv"
Const ForWriting = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")
'Asks for directory to search in
searchPath = InputBox("Please enter the path of the folder you would like to search", "Where am I searching?")
Set objFolder = objFSO.GetFolder(searchPath)
'Asks for the search term to use
searchTerm = InputBox("Please enter the term you would like to search for", "What am I searching?")
If objFSO.FileExists(objCheckFile) Then
WScript.Echo "Please delete the file named Audit.csv before trying again"
Else
Set objWriteFile = objFSO.CreateTextFile("Audit.csv", ForWriting, True)
End If
Set colFiles = objFolder.Files
Set colFolders = objFolder.SubFolders
'Searches for files within the folder and writes to a CSV file
For Each objFile In colFiles
If InStr(LCase(objFSO.GetFileName(objFile)), LCase(searchTerm)) > 0 Then
objWriteFile.Write objFSO.getFileName(objFile) & ", "
objWriteFile.Write objFile.size & ", "
objWriteFile.Write objFile.DateLastModified & ", "
objWriteFile.Write objFSO.getAbsolutePathName(objFolder) & objFSO.getFileName(objFile)
objWriteFile.Writeline
End If
Next
ShowSubFolder objFolder
Sub ShowSubFolder(Folder)
If InStr(LCase(objFSO.GetFileName(objFile)), LCase(searchTerm)) > 0 Then
objWriteFile.Write objFSO.getFileName(objFile) & ", "
objWriteFile.Write objFile.size & ", "
objWriteFile.Write objFile.DateLastModified & ", "
objWriteFile.Write objFSO.getAbsolutePathName(objFolder) & objFSO.getFileName(objFile)
objWriteFile.Writeline
End If
For Each objSubFolder In colFolders
ShowSubFolder objSubFolder
Next
End Sub
Your recursion never terminates because of this:
Set colFiles = objFolder.Files
Set colFolders = objFolder.SubFolders
'...
ShowSubFolder objFolder
Sub ShowSubFolder(Folder)
'...
For Each objSubFolder In colFolders
ShowSubFolder objSubFolder
Next
End Sub
This is similar to a fork bomb. For each subfolder of objFolder you recurse again into each subfolder of objFolder. And again. And again. And ...
Change your code to this and it should do what you want:
Set colFiles = objFolder.Files
'...
ShowSubFolder objFolder
Sub ShowSubFolder(Folder)
'...
For Each objSubFolder In Folder.SubFolders
ShowSubFolder objSubFolder
Next
End Sub
You may also want to adjust the conditional inside the recursive procedure, because it uses objFile and objFolder that are defined outside the procedure.

Vbscript to search for all files with an extension and save them to a CSV

I am trying to write a script that will search say C:\ and all of its sub folders for a specific extension and save all of theme to a CSV file. I have tried this but to no avail:
Set objFSO = CreateObject("Scripting.FileSystemObject")
objStartFolder = "C:\"
Set objFolder = objFSO.GetFolder(objStartFolder)
Wscript.Echo objFolder.GetExtensionName("*.txt")
Set colFiles = objFolder.Files
For Each objFile in colFiles
If objFile.Extension = "pfx" Then
Wscript.Echo objFile.Name
End If
Next
Wscript.Echo
ShowSubfolders objFSO.GetFolder(objStartFolder)
Sub ShowSubFolders(Folder)
For Each Subfolder in Folder.SubFolders
Wscript.Echo Subfolder.Path
Set objFolder = objFSO.GetFolder(Subfolder.Path)
Set colFiles = objFolder.Files
For Each objFile in colFiles
Wscript.Echo objFile.Name
Next
Wscript.Echo
ShowSubFolders Subfolder
Next
Set WScript = CreateObject("WScript.Shell")
End Sub
I don't think I am going down the right path here. I am not proficient in the least in vb script it just happens to be the only thing I am allowed to use.
Here you go:
Option Explicit 'force all variables to be declared
Const ForWriting = 2
Dim objFSO
Set objFSO = CreateObject("Scripting.FileSystemObject")
Dim objTS 'Text Stream Object
Set objTS = objFSO.OpenTextFile("C:\Output.txt", ForWriting, True)
Recurse objFSO.GetFolder("C:\")
objTS.Close()
Sub Recurse(objFolder)
Dim objFile, objSubFolder
For Each objFile In objFolder.Files
If LCase(objFSO.GetExtensionName(objFile.Name)) = "pfx" Then
objTS.WriteLine(objfile.Path)
End If
Next
For Each objSubFolder In objFolder.SubFolders
Recurse objSubFolder
Next
End Sub
I know this is somewhat late, but that's the hard way to get that list. easiest is to sue the command line:
first identify the file where you want the directories like this:
set FileList="C:\path\path\file.csv"
Second identify the starting directory like this:
set Start="C:\path\path"
Then fill it like this:
for /F "usebackq" %i in (`dir /s/b "%Start%\*.pfx"`) do echo %~pi>>%filelist%
Done and done interactively.
PS - the post took out the backticks. That's the character usually under the tilde and they should enclose the complete directory command. Assuming a replace of ! for the backtick tick, the drectory command shold be !dir/s/b "%Start%\*.pfx"!
Later still but even simpler (and fast :0)):
Open a CMD, CD to the directory in question
DIR /S /A-D /B C:\*.something >> D:\ListOf.Files

VBScript: Getting error by batch renaming files within a folder

In this script I try to rename all the files within a folder. The new names I will gather from each textfiles in itself using Instr(1, strText, "(Amtlicher Gemeindeschlüssel = " ...). So all jsp-files shall be proceed. But I get an object-error almost at the end: 800A01A8 - Object Required. Can anyone helpme to replace the object strVerz.files so the the code works.
Thank U in advance.
Michael
Dim objFso, strFolder
' Begin Main
Set objFso = CreateObject("Scripting.FileSystemObject")
strFolder = objFso.GetParentFolderName(WScript.ScriptFullName)
If objFso.FolderExists(strFolder) Then
Call GetJspFiles(objFso.GetFolder(strFolder))
End If
Set objFso = Nothing
' End Main
Sub GetJspFiles(ByRef objFolder)
Dim objFile, objSubFolder
For Each objFile In objFolder.Files
If LCase(objFso.GetExtensionName(objFile.Name)) = "jsp" Then
Call JSPRename(objFile.Path, objFolder.Path)
End If
Next
For Each objSubFolder In objFolder.SubFolders
Call GetJspFiles(objSubFolder)
Next
' objFile.Close
End Sub
Sub JSPRename(ByRef strPath, ByRef strFolder)
Dim arrText, strText, strTextLine, Position , objJspFile, newFilename, strVerz
Set objJspFile = objFso.OpenTextFile(strPath)
arrText = Split(objJspFile.ReadAll, vbCrLf) ' split to lines
For Each strTextLine In arrText
If strTextLine <> "" Then
strText = Trim(strTextLine)
If Instr(1,strText,"(Amtlicher Gemeindeschlüssel",1) Then
Position=Instr(1, strText, "(Amtlicher Gemeindeschlüssel =",1)
newFilename=mid(strText,Position+31, 8)
else
end if
end if
Next
strVerz=objFSO.GetParentFoldername(WScript.ScriptFullName)
strNewName = strVerz & "\" & newFilename & ".jsp"
' Wscript.echo strNewName & vbcrlf & strVerz.files '!! only for Showing the results
objFSO.MoveFile strVerz.files, strNewName <- Here I get the error
objJspFile.Close
End Sub
It seems like the purpose of JSPRename is to rename the file given by strPath. In that case, the call to MoveFile should look like:
objFSO.MoveFile strPath, strNewName

Resources