VBscript comparing md5 "If then" - vbscript

I am trying to compare some Md5's of some files to see if they are the same after I have copied them to another drive, and if they are the same then to delete the original files. I am lost on the syntax because I have never done something like this before.
I am using a free utility vmd5.exe (command line) to get the md5's. I am just not sure how to tell vbscript that if the outputs are the same then to go ahead and delete the files. This is just a snippet of the part where I am trying to compare the two md5's but this is what I have so far:
Dim md5Command, md5Command2
md5Command = "C:\Program Files\vmd5.exe " vmd5 & " " & C:\Testscripts\
md5Command2 = "C:\Program Files\vmd5.exe " vmd5 & " " & E:\CopyTestFolder\
If md5Command = md5Command2 then
objFSO.DeleteFolder("C:\ScriptOutput") 'Can either delete entire archived folder, or just .zip files in folder
objFSO.DeleteFile("C:\Testscripts\Archive*.evtx") 'This will be path where archived logs are located once finished
Else
End If
This syntax is wrong for sure. But from what I know about IF then's I need it to look something like this. I am just not sure if I need to be telling the script to run the commands in the "set" part or how I can tell the script to grab the md5 output from the command line and compare it to another.
After the Else statement I would like it to either end the script or just output a text file with the different md5's but I am not to that point yet and haven't really decided on anything.
If there is a better way to do something like this I would also be up to do that, this is about all I was coming up with this morning though.
EDIT: I thought of something that might be possible. If I tell the command line to output the contents of the output to a text file then I could compare two different text files and if the contents match then it could proceed with the rest of the script. I don't know how to get this to work but the logic seems to make sense.
Here is what the output of the text file that it creates looks like:
Vallen VMD5 R2009.1215
Filename MD5 sum
------------------------------------------------------------
[C:\ScriptOutput\]
Testzip.zip d5db2ff8c372a12c145170fb7340e682

To tackle your task, you have to solve some sub problems:
String concatenation in VBScript: "... exe " vmd5 & " " - to splice in the content of the variable vmd5, you need the concatenation operator on both sides - but is that what you want to do? " " & C:\Testscripts\ - to append the literal 'C:\Testscripts\', you need to (double) quote the literal - but then you could combine all the components into one string literal.
In VBScript " are used as string literal delimiters; they don't work like backticks in more powerful scripting languages. md5Command must hold the command you want to execute; to get the result of that command is a different kettle of fish.
To shell out/execute a command, you'll have to use the .Exec or the .Run method of the WScript.Shell object and collect the output.
Depending on the (output of) the tool you use, you won't be able to compare the results via the = operator - e.g. the pathes or the order of the files/cheksums may differ. So you'll need a strategy for parsing the captured output.
Which sub problem do you want to deal with first?
As your comments prove, getting the syntax right should be the starting point. This:
Dim aDirs : aDirs = Array("..\data\one", "..\data\two")
' Join an array of the components (no more problems
' with (forgetting (to concat)) separators)
' Use qq() function to lessen the noise
Dim sCmdT : sCmdT = Join(Array( _
"fciv" _
, "-add" _
, qq("§DIR§") _
), " ")
Dim nDir, sDir, sCmd
For nDir = 0 To UBound(aDirs)
sDir = aDirs(nDir)
' Use replace on a template to avoid repetition
sCmd = Replace(sCmdT, "§DIR§", sDir)
WScript.Echo "sCmd: |" & sCmd & "|"
Next
output:
sCmd: |fciv -add "..\data\one"|
sCmd: |fciv -add "..\data\two"|
illustrates 3 methods to make it easier/less errorprone to 'build' (shell) commands or SQL statements. (Implementation of the qq() function is left as exercise).
As I don't have the vmd5 utility, I'll use fciv in the further examples.
The next (version of the) script:
Dim aDirs : aDirs = Array("..\data\one", "..\data\two")
Dim sCmdT : sCmdT = Join(Array( _
"fciv" _
, "-add" _
, qq("§DIR§") _
), " ")
Dim oWSH : Set oWSH = CreateObject("WScript.Shell")
Dim nDir, sDir, sCmd, oExec, sRes
For nDir = 0 To UBound(aDirs)
sDir = aDirs(nDir)
sCmd = Replace(sCmdT, "§DIR§", sDir)
Set oExec = oWSH.Exec(sCmd)
sRes = oExec.Stdout.ReadAll()
WScript.Echo sRes
Next
output:
CmpMd500 - compare md5 checksums
==============================================================
//
// File Checksum Integrity Verifier version 2.05.
//
09fea378b96141413f5f09444573f0f3 ..\data\one\version.txt
4945c1ffd9ceb14c83e003091c6e8455 ..\data\one\README.md
4c4c34f7b6f0863056615d2cbcdf6912 ..\data\one\History.txt
//
// File Checksum Integrity Verifier version 2.05.
//
09fea378b96141413f5f09444573f0f3 ..\data\two\version.txt
4945c1ffd9ceb14c83e003091c6e8455 ..\data\two\README.md
4c4c34f7b6f0863056615d2cbcdf6912 ..\data\two\History.txt
==============================================================
demonstrates the absolute minimum of code to execute a command and capture the output - a production version must add a lot of code for error handling. At the same time, it shows sample output to discuss how to parse/compare the checksums. Can you post sample output of your vmd5 utility?
Whether you get the output of the md5 utility directly (my above sample) or from a file, you'll need a Regular Expression to parse the string into data that can be processed further. A simple script to work with files like you published in your question:
Dim reMd5File : Set reMd5File = New RegExp
reMd5File.Global = True
reMd5File.Multiline = True
reMd5File.Pattern = "^(\S+)\s+(\w{32})"
Dim sDir : sDir = "..\data\three"
Dim oFile
For Each oFile In goFS.GetFolder(sDir).Files
Dim sAll : sAll = oFile.OpenAsTextStream(ForReading).ReadAll()
WScript.Echo sAll
Dim oMTS : Set oMTS = reMd5File.Execute(sAll)
Dim oMT
For Each oMT In oMTS
WScript.Echo "** parsed:", qq(oMT.Submatches(1)), qq(oMT.Submatches(0))
Next
Next
output:
CmpMd501 - compare md5 checksums
==================================================================
Vallen VMD5 R2009.1215
Filename MD5 sum
------------------------------------------------------------
[C:\ScriptOutput\]
Testzip.zip d5db2ff8c372a12c145170fb7340e682
version.txt 09fea378b96141413f5f09444573f0f3
README.md 4945c1ffd9ceb14c83e003091c6e8455
History.txt 4c4c34f7b6f0863056615d2cbcdf6912
** parsed: "d5db2ff8c372a12c145170fb7340e682" "Testzip.zip"
** parsed: "09fea378b96141413f5f09444573f0f3" "version.txt"
** parsed: "4945c1ffd9ceb14c83e003091c6e8455" "README.md"
** parsed: "4c4c34f7b6f0863056615d2cbcdf6912" "History.txt"
********************
Vallen VMD5 R2009.1215
Filename MD5 sum
------------------------------------------------------------
[C:\ScriptOutput\]
Testzip.zip d5db2ff8c372a12c145170fb7340e682
** parsed: "d5db2ff8c372a12c145170fb7340e682" "Testzip.zip"
********************
==================================================================
xpl.vbs: Erfolgreich beendet. (0) [0.14844 secs]
After working thru that code, you'll have no problem with this script, that adds
'storing of the results in dictionaries' to my 'read .Exec output' version:
Dim aDirs : aDirs = Array("..\data\one", "..\data\two")
Dim sCmdT : sCmdT = Join(Array( _
"fciv" _
, "-add" _
, qq("§DIR§") _
), " ")
Dim oWSH : Set oWSH = CreateObject("WScript.Shell")
ReDim aRes(UBound(aDirs))
Dim reMd5File : Set reMd5File = New RegExp
reMd5File.Global = True
reMd5File.Multiline = True
reMd5File.Pattern = "^(\w{32})\s(.+?)\s+$"
Dim nDir, sDir, sCmd, oExec, sRes, oMTS, oMT
For nDir = 0 To UBound(aDirs)
sDir = aDirs(nDir)
sCmd = Replace(sCmdT, "§DIR§", sDir)
Set oExec = oWSH.Exec(sCmd)
sRes = oExec.Stdout.ReadAll()
Set aRes(nDir) = CreateObject("Scripting.Dictionary")
Set oMTS = reMd5File.Execute(sRes)
For Each oMT in oMTS
aRes(nDir)(goFS.GetBaseName(oMT.SubMatches(1))) = oMT.SubMatches(0)
Next
Next
Dim sFile
For nDir = 0 To UBound(aDirs)
For Each sFile In aRes(nDir).Keys
WScript.Echo aRes(nDir)(sFile), sFile
Next
WScript.Echo
Next
output:
===========================================
09fea378b96141413f5f09444573f0f3 version
4945c1ffd9ceb14c83e003091c6e8455 README
0252535193507019a0eb97328d28dd80 robic
4c4c34f7b6f0863056615d2cbcdf6912 History
09fea378b96141413f5f09444573f0f3 version
4945c1ffd9ceb14c83e003091c6e8455 README
4c4c34f7b6f0863056615d2cbcdf6912 History
c46264f8101b6c1609c77b4c674bd327 Rakefile
===========================================
The next - and last, I hope - step would be to do the comparisons (Are files missing from one folder?, Do the checksums for the 'same' file differ?). Any ideas from your side?

Related

Waiting while files are zipped in VBScript [duplicate]

I am using VBscript to scan folders, create zip files and add files to them (compress), but as I run my script on folders with a lot of files, I get the following error: "Compressed (zip) Cannot create output file"
my zip handling code is as follows:
Dim objFSO
Set objFSO= CreateObject("Scripting.FileSystemObject"
Function PreformZip(objFile,target,zip_name, number_of_file)
Set shell = CreateObject("WScript.Shell")
zip_target = target + "\" + zip_name +".zip"
If Not objFSO.FileExists(zip_target) Then
MakePathIfNotExist(target)
NewZip(zip_target)
Else
If number_of_file=0 Then
objFSO.DeleteFile(zip_target)
NewZip(zip_target)
End if
End If
Set zipApp = CreateObject("Shell.Application")
aSourceName = Split(objFile, "\")
sSourceName = (aSourceName(Ubound(aSourceName)))
zip_file_count = zipApp.NameSpace(zip_target).items.Count
zipApp.NameSpace(zip_target).Copyhere objFile, 16
On Error Resume Next
sLoop = 0
Do Until zip_file_count < zipApp.NameSpace(zip_target).Items.Count
Wscript.Sleep(100)
sLoop = sLoop + 1
Loop
On Error GoTo 0
End Function
Sub NewZip(zip)
Set new_zip = objFSO.CreateTextFile(zip)
new_zip.Write Chr(80) & Chr(75) & Chr(5) & Chr(6) & String(18, 0)
new_zip.Close
Set new_zip = Nothing
WScript.Sleep(5000)
End Sub
Function MakePathIfNotExist(DirPath)
Dim FSO, aDirectories, sCreateDirectory, iDirectory
Set FSO = CreateObject("Scripting.FileSystemObject")
If FSO.FolderExists(DirPath) Then
Exit Function
End If
aDirectories = Split(DirPath, "\")
sCreateDirectory = aDirectories(0)
For iDirectory = 1 To UBound(aDirectories)
sCreateDirectory = sCreateDirectory & "\" & aDirectories(iDirectory)
If Not FSO.FolderExists(sCreateDirectory) Then
FSO.CreateFolder(sCreateDirectory)
End If
Next
End Function
Function Recursion(DirectoryPath)
Dim FSO : Set FSO = CreateObject("Scripting.FileSystemObject")
If FSO.FolderExists(DirectoryPath) Then Exit Function
Call Recursion(FSO.GetParentFolderName(DirectoryPath))
FSO.CreateFolder(DirectoryPath)
End Function
I first thought I'm not waiting long enough after creating the zip, but I even tried it with 10 seconds wait after each zip and I still get the same error.
How can I solve it?
If there is no solution, is there an alternative way to make a zip? The script is not only for my own use so I don't want ro relay on a software which needs to be installed?
Although Folder.CopyHere method does not return a value and no notification is given to the calling program to indicate that the copy has completed, you could wait with next code snippet and I hope you can see proper (re)placement in your script:
On Error GoTo 0
zipApp.NameSpace(zip_target).Copyhere objFile _
, 4 +8 +16 +256 +512 +1024
Wscript.Sleep( 100)
On Error GoTo 0
Notice: no waiting Do..Loop, this Wscript.Sleep( 100) is sufficient to zip small files or start progress dialog box in case of huge files - and your script will wait for it...
Notice: no 'On Error Resume Next. Avoid invoking On Error Resume Next if you do not handle errors...
Flags used as follows.
Const FOF_SILENT = &h0004 'ineffective?
Const FOF_RENAMEONCOLLISION = &h0008 'ineffective?
Const FOF_NOCONFIRMATION = &h0010 '
Const FOF_SIMPLEPROGRESS = &h0100 'ineffective?
Const FOF_NOCONFIRMMKDIR = &h0200 '
Const FOF_NOERRORUI = &h0400 '
Unfortunately, in some cases, such as compressed (.zip) files, some option flags may be ignored by design (sic!) by MSDN!
If FOF_SILENT flag ineffective, then user could Cancel zipping process...
If FOF_RENAMEONCOLLISION flag ineffective, then newer file of the same name is not zipped, existing zip file keeps previous version without caution against; only existing folder brings on an extra error message...
Those could be fixed up as well, but it's subject of another question...
Well, after a great amount of research I found out that there is no possible way to fix this problem when using shell to perform zip.
I solved this issue by using za7.exe (7-zip) in the following way:
Dim zipParams
zipParams = "a -tzip"
Dim objShell: Set objShell = CreateObject("WScript.Shell")
command = zip_exe_location + " " + zipParams + " " + zip_target + " " + SourceFile
objShell.Run Command, 0 ,true
the "a" in the zip parameters means "add to file" and -tzip sets the type of the file as zip.

How to redirect output from EXE to TXT file using VBScript?

The requirement is to execute a certain script on multiple workstations using a tool such as Microsoft SCCM.
This script is required to execute the EXE 'C:\ugs\nx5\UGII\env_print.exe' on every workstation. This is to be done twice using the following parameters :
C:\ugs\nx5\UGII\env_print.exe -m
C:\ugs\nx5\UGII\env_print.exe -n
The script must be designed such that the output from the above mentioned should be stored at someplace on the workstation, from where SCCM could read the values.
To achieve this requirement, I wrote the following VBscript :
--------------------------------------------------------------------------------------------
On Error Resume Next
Const HKEY_LOCAL_MACHINE = &H80000002
Dim WshShell, fso, file, objRegistry, strKeyPath, strSysDrive, outputFile, strTEMP, file2, oTxtFile, oTxtFile2
Dim ComExec, strSysRoot, strComputer, outputFile2, EXEpath, ComExec2, return, return2, text, text2, CMDPath
strComputer = "."
Set WshShell = Wscript.CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
Set objRegistry = GetObject("winmgmts:\\" & strComputer & "\root\default:StdRegProv")
strSysDrive = WshShell.ExpandEnvironmentStrings("%SystemDrive%")
strSysRoot = WshShell.ExpandEnvironmentStrings("%SystemRoot%")
EXEpath = strSysDrive & "\ugs\nx5\UGII\env_print.exe"
CMDPath = strSysRoot & "\system32\cmd.exe"
'-----------------------SET TXT FILE LOCATION-----------------------
outputFile = strSysDrive & "\env_print_m.txt"
outputFile2 = strSysDrive & "\env_print_n.txt"
'-----------------------CREATE TEXT FILES-----------------------
Set oTxtFile = fso.CreateTextFile(outputFile)
Set oTxtFile2 = fso.CreateTextFile(outputFile2)
'-------COMMAND TO EXECUTE AND REDIRECT OUTPUT TO TXT FILE-------
ComExec = CMDPath & " /c " & EXEpath & " -m >> " & outputFile
ComExec2 = CMDPath & " /c " & EXEpath & " -n >> " & outputFile2
'-----------------------EXEUTE COMMANDS-----------------------
return = WshShell.Run(ComExec, 0, true)
return2 = WshShell.Run(ComExec2, 0, true)
'-----------------------READ OUTPUT FROM TXT FILES-----------------------
Set file = fso.OpenTextFile(outputFile, 1)
text = file.ReadAll
file.Close
Set file2 = fso.OpenTextFile(outputFile2, 1)
text2 = file2.ReadAll
file.Close
'-----------------------WRITE OUTPUT VALUES TO REGISTRY STRING VALUES-----------------------
strKeyPath = "SOFTWARE\env_print_Ver"
objRegistry.CreateKey HKEY_LOCAL_MACHINE, strKeyPath
WshShell.RegWrite "HKEY_LOCAL_MACHINE\SOFTWARE\env_print_Ver\env_print_m", text, "REG_SZ"
WshShell.RegWrite "HKEY_LOCAL_MACHINE\SOFTWARE\env_print_Ver\env_print_n", text2, "REG_SZ"
'-----------------------DELETE TXT FILES-----------------------
fso.DeleteFile outputFile
fso.DeleteFile outputFile2
--------------------------------------------------------------------------------------------
This script executes the EXE with the required parameters and stores the output to 2 different TXT files(env_print_m.txt and env_print_n.txt).
Then reads these string values from the text files and stores them as registry string values at the following locations, so that it could be read by SCCM.
HKEY_LOCAL_MACHINE\SOFTWARE\env_print_Ver\env_print_m
HKEY_LOCAL_MACHINE\SOFTWARE\env_print_Ver\env_print_n
However, when this script is executed on workstations running Windows XP, the outputs aren't redirected to the TXT files. No errors are displayed either.
I am at my wits end. Please help.
As your first output file is not named/specified outputFile, change
Set file = fso.OpenTextFile("outputFile", 1)
to
Set file = fso.OpenTextFile(outputFile, 1)
(Same for the second one)
Trying to access a file wrongly named should abort your script with an error message. You switched of this feature by an EVIL global "On Error Resume Next". Get rid of it and see if "outputs aren't redirected' is explained by an error message.
Added wrt comment:
If something like
WshShell.Run ComExec, 0, true
'does not work' you should:
call .Run as a function and check the return value
echo the command (ComExec) and try to execute exactly this command from a console
switch /c to /k and look
sacrify a goat and think about permissions
Oh, I forgot:
manually delete the output files and check if they are created but get no content - then reconder the .exe

VB script run time error input past end of file

I'm taking a scripting class and im having some issues with my script. According to the lab assignment all my syntax is correct. However i keep getting a input past end of file error on line 60,1. I've starred at the program forever and checked all lines letter for letter for quite some time with no luck. Any help would be greatly appreciated. Here is the script.
dim ipAddress(5,3)
ipAddress(0,0)="192.168.10.11"
ipAddress(0,1)="192.168.10.12"
ipAddress(0,2)="192.168.10.13"
ipAddress(0,3)="192.168.10.14"
ipAddress(1,0)="192.168.10.19"
ipAddress(1,1)="192.168.10.20"
ipAddress(1,2)="192.168.10.21"
ipAddress(1,3)="192.168.10.22"
ipAddress(2,0)="192.168.10.27"
ipAddress(2,1)="192.168.10.28"
ipAddress(2,2)="192.168.10.29"
ipAddress(2,3)="192.168.10.30"
ipAddress(3,0)="192.168.10.35"
ipAddress(3,1)="192.168.10.36"
ipAddress(3,2)="192.168.10.37"
ipAddress(3,3)="192.168.10.38"
ipAddress(4,0)="192.168.10.43"
ipAddress(4,1)="192.168.10.44"
ipAddress(4,2)="192.168.10.45"
ipAddress(4,3)="192.168.10.46"
ipAddress(5,0)="192.168.10.51"
ipAddress(5,1)="192.168.10.52"
ipAddress(5,2)="192.168.10.53"
ipAddress(5,3)="192.168.10.54"
const READ = 1
const WRITE = 2
const APPEND = 8
const ASCII = 0
dim fileName
fileName = "IP_Addresses.csv"
dim ipAddrStr
ipAddrStr = ""
dim fso
Set fso = Wscript.CreateObject("Scripting.FileSystemObject")
Set ipFileObj = fso.CreateTextFile(fileName,True,ASCII)
For room = 0 to 5
For computer = 0 to 3
ipAddrSr = CStr(room+100) & "," & CStr(computer+1) & "," ipAddress(room,computer)
& vbCrlf
ipFileObj.write(ipAddrStr)
Next
Next
ipFileObj.close
Set ipFileObj = fso.OpenTextFile(fileName,READ,ASCII)
WScript.Echo ipFileObj.ReadAll **' this is line 60**
ipFileObj.Close
As you don't use "Option Explicit", you get what you deserve: You (try to) concatenate the lines into ipAddrSr but write ipAddrStr to the file. So nothing gets written to the file.
Fix the syntax error and the bad name to:
ipAddrStr = CStr(room+100) & "," & CStr(computer+1) & "," & ipAddress(room,computer) & vbCrlf
Assuming that the file isn't empty, perhaps you need to specify the directory the file is in? I think this can be done either in your script:
fileName = "c:\your_directory\IP_Addresses.csv"
Or if you run it in the command line via cscript...
cscript.exe your.vbs "c:\your_directory\IP_Addresses.csv"
You can check the file size before executing your Echo if you like...
if fileName.size > 0 then
Set ipFileObj = fso.OpenTextFile(fileName,READ,ASCII)
WScript.Echo ipFileObj.ReadAll **' this is line 60**
ipFileObj.Close
else
WScript.Echo = "File was empty"
end if
See details of passing an argument to your script here.

Rename files without copying in same folder

I have files with following naming convention.
RE12356_GJ123456789.DAT
I need to rename the file to RE12356_GJ123456790.DAT without copying the files using VBS i.e. I need to increment by 1, everytime when I run VBS file. Please help me. Thanks!
The FileSystemObject has a method .GetFile(FileSpec) that returns an object for the file FileSpec. Those objects have a (writable) .Name property. So get the .Name, modify it, and write/assign the new one.
To give you some ideas (looping over the files in a folder, finding the file(s) to change, extracting the number to increment):
Option Explicit
Dim goFS : Set goFS = CreateObject( "Scripting.FileSystemObject" )
WScript.Quit demoMain()
Function demoMain()
demoMain = 0 ' assume success
Dim sDDir : sDDir = goFS.GetAbsolutePathName(".\")
Dim reVictim : Set reVictim = New RegExp
reVictim.IgnoreCase = True
reVictim.Pattern = "^(victim)(\d+)(\.txt)$"
Dim oFile
For Each oFile In goFS.GetFolder(sDDir).Files
If reVictim.Test(oFile.Name) Then
WScript.Echo "found: ", oFile.Name
oFile.Name = reVictim.Replace(oFile.Name, GetRef("FINC"))
WScript.Echo "renamed:", oFile.Name
End If
Next
End Function ' demoMain
Function FINC(sM, sG1, sG2, sG3, nP, sS)
FINC = sG1 & Right(100 + sG2 + 1, 2) & sG3
End Function
output:
cscript finc.vbs
found: victim00.txt
renamed: victim01.txt
cscript finc.vbs
found: victim01.txt
renamed: victim02.txt
cscript finc.vbs
found: victim02.txt
renamed: victim03.txt
How to copy with overflow of the counter is left as exercise.
You can just use the "move" command which will not actually rewrite the file but will just move the entry in the file table... which is essentially a "rename"
If you don't want to use filesystemobject.move you could issue a command line rename command via: Wsript.shell
like...
Dim objShell
Set objShell = WScript.CreateObject ("WScript.shell")
objShell.run "cmd /c rename somefile.txt newname.txt"
Set objShell = Nothing
or as Ekkehard.Horner pointed out:
Dim fso, f, s
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFile(filespec)
f.name = "newFileName.txt"
see: Name Property (FileSystemObject)

Find and replace multiple file in vbs

I am trying to implement a find and replace for all files in a folder using a vbs script, here is what I have so far
Dim fso,folder,files,oldFileContents,newFileContents,FIND,REPLACE
FIND = "textToBeReplaced"
REPLACE = "localhost"
Set fso = CreateObject("Scripting.FileSystemObject")
Set folder = fso.GetFolder("HTML")
Set files = folder.Files
For each item In files
oldFileContents = GetFile(item.Path)
newFileContents = replace(oldFileContents,FIND,REPLACE,1,-1,1)
WriteFile FileName,newFileContents
Next
but when I try to run it I get and error, "Type Mismatch: 'GetFile'", what am I doing wrong?
The problem should be solved with code like:
' Constants Mr Gates forgot (but cf. vbTextCompare)
Const ForReading = 1
Const ForWriting = 2
' Configuration constants
Const csFind = "pdf"
Const csRepl = "puf"
' Dim & init for vars needed on *this* level
Dim oFS : Set oFS = CreateObject("Scripting.FileSystemObject")
Dim sTDir : sTDir = oFS.GetAbsolutePathName("..\data\test")
Dim oFile
For Each oFile In oFS.GetFolder(sTDir).Files
WScript.Echo "looking at", oFile.Name
' Dim & init for vars needed on *this* level
Dim sContent : sContent = goFS.GetFile(oFile.Path)
' For Skytunnels and other air-coders
WScript.Echo "content is not", sContent
' you got oFile, so use it; no need for .GetFile()
sContent = oFile.OpenAsTextStream(ForReading).ReadAll()
WScript.Echo "qed! content is", sContent
' Replace(expression, find, replacewith[, start[, count[, compare]]])
' don't use magic numbers; vbTextCompare is even pre-defined
sContent = Replace(sContent, csFind, csRepl, 1, -1, vbTextCompare)
WScript.Echo "new content", sContent
oFile.OpenAsTextStream(ForWriting).Write sContent
sContent = oFile.OpenAsTextStream(ForReading).ReadAll()
WScript.Echo "new content straight from file", sContent
WScript.Echo "------------------"
Next
output:
...
------------------
looking at 0000000000012345.20120302.pdf
content is not E:\trials\SoTrials\answers\9117277\data\test\0000000000012345.20120302.pdf
qed! content is This is the content of 0000000000012345.20120302.pdf
new content This is the content of 0000000000012345.20120302.puf
new content straight from file This is the content of 0000000000012345.20120302.puf
Important points:
Don't use a Dim-all-vars-ever-used-line at the top of your script
Avoid creation of unnecessary vars (folder, files, *contents), use
the vars you have properly (item==oFile)
.GetFile() returns a File object, not the file's content
You missed out the fso. on
oldFileContents = fso.GetFile(item.Path)
and
fso.WriteFile FileName,newFileContents
EDIT: as per discussion below, please note this answer was only meant to show where your error was occurring. It was assumed that your intent was to develop your code further once your got past this error, which if so, I’m sure you’ve already seen Ekkehard has provided some very helpful guidance on his answer.

Resources