Inserting Lines into a Non-Text File - vbscript

I am trying to insert lines into the middle of a non-text file (the extension of the file is "dxf"). I am using vbscript to do this.
Everywhere I have look, I come across the FileSystemObject.OpenTextFile. However, when I try to use this on a dxf file, it is causing an error: Exception 80070057 (I believe this is an invalid file) .
Here is my code:
Dim file
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
If fileexists(dxfFile$) Then
Set file = fso.OpenTextFile(dxfPath, ForAppending, True)
file.WriteLine("<PORTLIST TESTING>ASDFLKJ")
file.Close
End If

dxfFile$ is not a valid VBscript variable name; use dxfFile, file or dfxPath (consistently)
FileExists is a method of the FileSystemObject; you need to call fso.FileExists
Neither dxfFile, nor dfxPath, nor ForAppending are defined
Calling .OpenTextFile with an undefined/empty first/filespec parameter throws an error 5 - Invalid procedure call or argument
You can't insert lines by appending them; modifying files 'in the middle' is especially clumsy in VBScript; loading the whole file into memory, editing, writing it back may work for you
.DFX file come in ASCII or binary format; if the latter, you can't use the FileSystemObject (see ADODB.Stream)

Related

VBsscript (.vbs) code gets cleared/removed

At the top of most of my VBscripts (.vbs files) I have the following code:
Option Explicit
Const ForReading = 1
Dim objFSO, objFile
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("Z:\somepath\somefile.vbs", ForReading)
Execute objFile.ReadAll()
This code allows me to use another vbs file as a library. In this case somefile.vbs would be my library and have all my subs and functions defined that are called from the script the above code is called from (I call this the calling script).
This issue: Every once in a while, one of the scripts seems to delete the code in Z:\somepath\somefile.vbs (the library script read by the calling script).
I think this because if a wscript.exe is listed in my Task Manager Processes tab and I restore the Z:\somepath\somefile.vbs file from a backup location, almost immediately, when I open Z:\somepath\somefile.vbs again, there is no code in that file. But if I kill the wscript.exe process, the file is fine. I can't reproduce the behavior because it only occurs when our network has a hiccup of some kind (I think).
My first thought is that the create setting is wrong when I use this line:
Set objFile = objFSO.OpenTextFile("Z:\somepath\somefile.vbs", ForReading)
But according to this link, the default create value should be false:
https://msdn.microsoft.com/en-us/library/aa265347(v=vs.60).aspx
Note, coincidentally, I am also using objFile and objFSO variables in the file somefile.vbs for things that aren't related to what I am doing in the calling script. For example, the objFile in the somefile.vbs file has a completely different name and location and is created this way:
Set objFile = objFSO.OpenTextFile("z:\differentpath\differentname.vbs", ForAppending, True)
I am guessing this is the issue, but I don't understand it. Can someone shed some light on this? Is the create or append setting getting reset in the calling script? How does that work?
Not knowing what else to do I have change the variable names in the somefile.vbs file to oFSO, oFile and in the calling script they are still objFSO, objFile. I also changed the line of code in the calling script to include false for the create setting like this:
Set objFile = objFSO.OpenTextFile("Z:\somepath\somefile.vbs", ForReading,false)
Going out on a limb (since you posted only partial code) I'm going to assume that you don't explicitly close your library script after reading, so your main script keeps the file open until it terminates. Either add a line objFile.Close after the Execute statement, or (better yet) change
Set objFile = objFSO.OpenTextFile("Z:\somepath\somefile.vbs", ForReading)
Execute objFile.ReadAll()
to
code = objFSO.OpenTextFile("Z:\somepath\somefile.vbs").ReadAll
Execute code
or just
Execute objFSO.OpenTextFile("Z:\somepath\somefile.vbs").ReadAll
so that the file is automatically closed after being read.
Learned from https://ss64.com/vb/execute.html
Execute takes a group of statements and executes them in local scope, ExecuteGlobal executes them in global scope.
However, if the same Execute statement is invoked outside of a procedure (i.e., in global scope), not only does it inherit everything in global scope, but it can also be called from anywhere, since its context is global.
Does the issue remain if you call the Execute form a procedure?

Replace a text file which may or may not contain a space in file name

I want to replace a file named with different name using VBScript. The input file name may or may not contain blank spaces.
Set objFSO = CreateObject("Scripting.FileSystemObject")
' First parameter: original location\file
' Second parameter: new location\file
objFSO.CopyFile "D:\Development\abc def.txt", "D:\Development\xyz.txt"
Perhaps surprisingly, CopyFile creates a copy of the source file. To rename a file you could use MoveFile, but the usual approach is to simply change the name of the file:
Set fso = CreateObject("Scripting.FileSystemobject")
fso.GetFile("D:\Development\abc def.txt").Name = "xyz.txt"
Edit: If you actually mean to replace one file with another file, you can do so with CopyFile by setting the third parameter (overwrite) to True, as #Lankymart pointed out in the comments.
fso.CopyFile "D:\Development\abc def.txt", "D:\Development\xyz.txt", True
If you don't want to keep the source file you need to delete it after the copy operation (VBScript doesn't allow moving a file over an existing file). Alternatively you can delete the destination file first and then move or rename the source file.

Why does VBS not read this text file correctly?

I have the following code to read a text file:
Option Explicit
Dim InputFile
Dim FSO, oFile
Dim strData
InputFile = "C:\Program Files (x86)\AVG\CloudCare\ClientVersion.txt"
Set FSO = CreateObject("Scripting.FileSystemObject")
Set oFile = FSO.OpenTextFile(InputFile)
strData = oFile.ReadAll
oFile.Close
msgbox strData
The contents of ClientVersion.txt is:
CLIENT_VERSION_STRING _T("3.5.2") //
When I run the VBS code, I get back this:
If I create a new text file with the same content in the same location, it works fine. Is there a reason why VBS is unable to read this simple text file? I couldn't see any issues with permissions on the file.
ÿþ is the byte order mark of a UTF-16 Little Endian encoded file. UTF-16 (unlike ASCII/ANSI) uses two bytes for a character instead of just one. However, the OpenTextFile method reads files as ASCII files by default, so each 2-byte character gets interpreted as two separate characters.
From the documentation:
Syntax
object.OpenTextFile(filename[, iomode[, create[, format]]])
Arguments
[…]
format
Optional. One of three Tristate values used to indicate the format of the opened file (TristateTrue = -1 to open the file as Unicode, TristateFalse = 0 to open the file as ASCII, TristateUseDefault = -2 to open the file as the system default). If omitted, the file is opened as ASCII.
Specify the proper encoding when reading the file and the problem will disappear:
Set oFile = FSO.OpenTextFile(InputFile, 1, False, -1)

How to parse one text file to multiple files based on data contained within

I have an enormous text file that I'd like to parse into other files - I think the only thing I have on this box (company computer) to use is VBS, so here's my question:
I have text file with a bunch of network configurations that looks like this:
"Active","HostName","IPAddress"
!
.......
end
This repeats itself throughout the file, but obviously for each configuration different data will occur within the "..." It always says "Active" for each configuration as well.
I want to create save files of the type HostName.cfg for each configuration and save all of the text between and including the ! and "end" . The line with the three quoted attributes doesn't need to be copied.
I'm still learning VBS so I'd appreciate any help in the matter. Thanks!
Here are some useful file reading functions and statements:
Freefile
Returns an integer which you should assign to a variable and then use in an Open statement.
Open <string> For Input As <integer>
Opens the specified file using the specified file handle. Don't use the same file handle twice without closing it in between.
Line Input #<integer>, <variable>
Reads one line of the file into a string.
Input #<integer>, <variable>, <variable>, <variable>
Reads one line of the file delimited by commas into several variables.
I once had to read a text file while omitting starting and ending lines. Though I didn't need to write it anywhere, FSO is simple enough that you will be able to figure it out. Here's some code for reading a file and link for writing to file via FSO: link
'Create a FSO object and open the file by providing the file path
Dim fso, f, filePath, line
filePath = "test.txt"
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(filePath)
'Skip through the first two lines
f.readline
f.readline
'Read till the end of file, if the line is not "end", split it based on ","
while not f.AtEndOfStream
line = f.readline()
if line <> "end" then
arr = split(line, ",")
'Write the arr to file
end if
wend
f.Close

creation of a text file in a specified location and remove the old one

I need to create a text file "setup.txt" in the location C:\Documents and Settings\All Users\Application Data\xerox\setapp in VB script
the location C:\Documents and Settings\All Users\Application Data is common apllication data folder here we can
use word "CSIDL_COMMON_APPDATA" or &H23& for that.Here the other which i need to take care is if any setup.txt file are
already there in that location i need to remove that old one i need to insert the new "setup.txt" which contatin blank
values means new one
I am new to this vbscript ,and i wanted an optimized code to acheive that functionality
You could open the file for writing and write a blank line, this will create the new text file and overwrite any previous versions.
strFilename = " C:\Documents and Settings\All Users\Application Data\xerox\setapp.txt"
Set objFile = CreateObject("Scripting.FileSystemObject").OpenTextFile(strFilename,2,true)
'Write stuff to the file here
objFile.Close
Set objFile = nothing
It's not clear if your script is creating the log file, if not and you want to copy the file and overwrite any previous ones you could do this (setting the last argument in the CopyFile method to true will overwrite older versions).
Set fso = CreateObject("Scripting.FileSystemObject")
fso.CopyFile Source, Destination, true
Set fso = Nothing
If you just want to delete the previous file if it exists you could do this (here setting the last argument in the DeleteFile method to true will force deletion of the file).
Set fso = CreateObject("Scripting.FileSystemObject")
If fso.FileExists(file) Then
fso.DeleteFile file, true
End If
Set fso = Nothing
Wow, VBScript, it was a long time ago ... But I'll give it a shot.
What you need, if I understand you correctly, is to use the FileSystemObject it contains methods for deleting, creating and copying text files.
I hope this at least gives you some pointers to get you started.

Resources