VB Script Text File Prepend - vbscript

Anyone know how to quickly prepend (add two new lines of text) to the start of an existing text file using either VB Script or a Bat file? Most elegant solution gets the tick.

How about this:
Dim fso, f
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile("test.txt", 1)
ReadAllTextFile = f.ReadAll
Set f = fso.OpenTextFile("test.txt", 2, True)
f.WriteLine("Blaaa")
f.WriteLine("Blaaaa some more...")
f.Write(ReadAllTextFile)
Source: Tek Tips

Check José Basilios answer for code and reference to the FSO. You will be using that.
BUT: I wouldn't go the ReadAllTextFile = f.ReadAll route, since that could be a few Gigabytes (who knows?).
INSTEAD:
open a new file
write prepended lines
read line by line from old file, writing into new file
(close both files)
delete old file
rename new file -> old file

Related

pasting a value to xlsx using shell

I have a template file in xlsx format and I want to paste a dynamic value in one particular cell i.e based on the flow of program the value in that cell will change which in turn changes conditions in xlsx file for a different process.
I have tried codes like
awk -v value=$value -v row=$row -v col=$col 'BEGIN{FS=OFS="#"} NR==row {$col=value}1' file.csv
but the issue is I cant use this code for xlsx file format. is there any way to do this for xlsx file format, since it's a template file I need to retain xlsx file format.
When I have to extract values from an Excel workbook on my Windows PC I install cygwin and then write a small shell script that does:
cygstart "/path/to/xls2csv.vbs" 'C:/cygwin64/path/to/bookName.xlsx'
awk 'whatever' '/path/to/bookName/sheetName.csv'
and the work of extracting every sheet from the workbook as a separate CSV named based on the sheet name suffixed with ".csv" under a common directory named after the workbook is done by this visual basic script:
$ cat xls2csv.vbs
csv_format = 6
Dim strFilename
Dim objFSO
Set objFSO = CreateObject("scripting.filesystemobject")
strFilename = objFSO.GetAbsolutePathName(WScript.Arguments(0))
If objFSO.fileexists(strFilename) Then
Call Writefile(strFilename)
Else
wscript.echo "no such file!"
wscript.echo strFilename
End If
Set objFSO = Nothing
Sub Writefile(ByVal strFilename)
Dim objExcel
Dim objWB
Dim objws
Set objExcel = CreateObject("Excel.Application")
Set objWB = objExcel.Workbooks.Open(strFilename)
For Each objws In objWB.Sheets
objws.Copy
objExcel.ActiveWorkbook.SaveAs objWB.Path & "\" & objws.Name & ".csv", csv_format
objExcel.ActiveWorkbook.Close False
Next
objWB.Close False
objExcel.Quit
Set objExcel = Nothing
End Sub
That command would fail given blanks in file or directory names so we need to replace those with, say, underscores. In reality I usually copy the Xls file to a temp directory and give it a temp name before running the above on it so I can run the above on it without affecting the original file and without having to care about the path to the original file. It requires an absolute path to the input Excel workbook.
You might need to throw a wait and/or sleep in before the awk command to ensure the VB script is done before the awk command runs. My not shown shell code is kinda convoluted testing for the VB script creating then removing tmp files to ensure the VB script is done and looping trying and then killing Excel if it doesn't start or hangs before calling awk - I wrote it a long time ago, it's a mess, and I doubt if it's really necessary or a good approach which is why I'm not including it here.
To get those values back INTO a multi-sheet workbook you'd have to open any updated/generated CSV with Excel (or copy/paste). There's probably some other VB script could be written to import the CSVs for you just like I export them above but I've never needed that functionality so idk what that'd look like.
I don't know if you need that though - if your awk script writes CSV then you can just double click on the output .csv and Excel will happily open and display it just like it would any .xls or .xlsx Excel file.
So, to do what you want, assuming your original content is in "Sheet1" of single-sheet Excel workbook "MyStuff.xlsx" you'd do this from cygwin:
cygstart "/path/to/xls2csv.vbs" 'C:/cygwin64/path/to/MyStuff.xlsx'
wait; sleep 10 # or similar
awk -v value="$value" -v row="$row" -v col="$col" 'BEGIN{FS=OFS=","} NR==row {$col=value}1' '/path/to/MyStuff/Sheet1.csv' > "/tmp/tmp$$" &&
mv "/tmp/tmp$$" '/path/to/MyStuff/Sheet1.csv'
and then in Windows just double-click on /path/to/MyStuff/Sheet1.csv to open it in Excel (you may need to associate the .csv file suffix with Excel the first time you do that).
Note that the above will only handle simple CSVs, see What's the most robust way to efficiently parse CSV using awk? for how to robustly handle CSVs with awk in general.

Reading Code inside Action in QTP

I want to read the code written inside an action in QTP,just as we read text file using FileSystem Object.
Is there any way to read code written in action line by line ?
So basically an action is attached to a QTP-Testcase. When you save this test case at a certain location, the code you have written is saved inside the directory named action1 or whatever action you were editing. In this folder you will find a file named script.AVCHD file. Open this in notepad and you will find your code inside it. Now all you got to do is write a simple visual basic, (or just any script you like) that will open this file and readall of the content into a variable. see if this helps. thanks.
For each test there will script.mts inside the Action1 folder.
get the script text line
filename = "C:\YourUFTTest\Action1\script.mts"
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(filename)
Do Until f.AtEndOfStream
msgbox f.ReadLine
Loop
f.Close

Move files older than x minutes

I want the script to move all files (all file extensions *.*) older than 5 minutes from an INN folder to and ERROR folder. In my example C:\CopyFlow\Directory test\Inn\ to C:\CopyFlow\Directory test\Inn\Error
So I figured how to move files and how to find files older than x-time after looking it up. Howover, putting this together is the issue for me. Does anyone know how I can nail this?
This is what I got so far...
Dim age_threshold
age_threshold = 5
Dim folder_path
folder_path = WScript.Arguments(0)
Dim fso, f
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.getFolder(folder_path)
Dim old_file_not_found
old_file_found = 0
For Each file in f.Files
Dim age
age = DateDiff("n", file.DateLastModified, Now)
If age > age_threshold Then
old_file_found = 1
.MoveFile "C:\CopyFlow\Directory test\Inn\*.*", "C:\CopyFlow\Directory test\Inn\Error"
Exit for
end if
Next
WScript.Quit
I'm used to batch, so this is a little bit greek to me (source http://www.evalesco.com/check-any-file-older-x-minutes-directory).
Now where do I set (dim?) my INN and ERROR folder in this script? And I'm pretty sure the if age followed by .movefile is wrong, so I probably need a little correction there.
Update Whats missing in the image is a backslash after error (\error\) in the move.file line.
You can't call methods without an object providing the method, so .MoveFile should be fso.MoveFile. However, in its current form the script would move all files from C:\CopyFlow\Directory test\Inn if any of the files in the folder passed as argument to the script is older than 5 minutes.
What you need to do is pass C:\test\inn as the argument to the script, and move only those files that actually are older:
If age > age_threshold Then
file.Move "C:\test\inn\error\"
End If

Need to write filenames to a text file

I am very new to VB Scripting and I am looking to see if there is a way to look at a directory get the file names and then write those file names to a text file. I would think that the Path.GetFileName Method would work, but I can't seem to get it to work. Maybe I am using it the wrong way.
Here is a simple script that will echo the filenames in the "C:\Windows\" directory.
Set fs = CreateObject("Scripting.FileSystemObject")
'Log file name
Set logFile = fs.OpenTextFile("fileNameLogs.txt", 2, True)
'Directory you want listed
Set folder = fs.GetFolder("c:\windows\")
Set files = folder.Files
For Each file in files
wscript.echo file.name
logFile.writeline(file.name)
Next
logFile.close

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

Resources