Read from array one by one - VBScript - arrays

I am trying to read from a file, create an array, then write to a second file line by line (element by element) while adding some additional information. The script below will read correctly from a file, but will only write the last line in the initial file. How can I write from the array one at a time? (I can write the contents to the second file in a different manner, but I want to do it directly from the array).
Const ForReading = 1, ForWriting = 2, ForAppending = 3
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(input,
ForReading)
Do Until objFile.AtEndOfStream
strLine = objFile.ReadLine
arrFields = Split(strLine, ",")
If InStr(arrFields(1), "False") Then
strContents = strContents & arrFields(0) & vbCrlf
End If
Loop
objFile.Close
Set objFile = objFSO.CreateTextFile(output)
' below correctly outputs contents
' objFile.Write strContents
For each i in arrFields
objFile.Write arrFields(0)
objFile.Write "Number" & vbCrlf
Next
objFile.Close
My test csv file reads as below saved as "test.csv" from notepad.
1,FALSE
2,FALSE
3,FALSE
4,FALSE
5,FALSE
6,FALSE
7,FALSE
8,FALSE
9,FALSE
10,FALSE
11,FALSE
12,FALSE
13,TRUE

Sample code
Const ForReading = 1, ForWriting = 2, ForAppending = 3
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\Users\pankaj.jaju\Desktop\test.csv", ForReading)
arrFields = Split(objFile.ReadAll, vbCrLf)
objFile.Close
Set objFile = objFSO.CreateTextFile("C:\Users\pankaj.jaju\Desktop\test1.txt")
For i = LBound(arrFields) To UBound(arrFields)
objFile.Write "Number " & i+1 & "," & Split(arrFields(i),",")(0) & vbCrlf
Next
objFile.Close

Related

How to find and read file using wild cards with VBscript?

I am trying unsuccessfully to read an XML file (The file name is change in each computer).
How it possible to read the file using wild card?
for example: D:\Logs\*.xml
Script:
Const ForReading = 1
Const ForWriting = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("D:\Logs\*.xml", ForReading)
strText = objFile.ReadAll
objFile.Close
strNewText = Replace(strText, "server1 ", "server889 ")
Set objFile = objFSO.OpenTextFile("D:\Logs\*.xml", ForWriting)
objFile.WriteLine strNewText
objFile.Closeenter code here
There is no wild card in VBScript. Repeat your group of statements for each element in Files collection of Folder object obtained by GetFolder Method:
Const ForReading = 1
Const ForWriting = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder("D:\Logs")
Set colFiles = objFolder.Files
For Each oFile in colFiles
If UCase(objFSO.GetExtensionName(oFile.name)) = "XML" Then
Set objFile = objFSO.OpenTextFile(oFile.Path, ForReading)
strText = objFile.ReadAll
objFile.Close
If Instr( 1, strText, "server1 ", vbTextCompare) > 0 Then
strNewText = Replace(strText, "server1 ", "server889 ", 1, -1, vbTextCompare)
Set objFile = objFSO.OpenTextFile(oFile.Path, ForWriting)
objFile.WriteLine strNewText
objFile.Close
End If
End If
Next
Resource: FileSystemObject

VBS script to copy files and folders across network

I needed to copy all of my photos from my old laptop to my new laptop. This is a quick and dirty script that I put together (based on other scripts on this site) to copy files from one network location to another. I wanted the process to be able to recover in case of a network copy error because the total time to copy all of my photos was 40 hours.
sourceRoot and targetRoot is the beginning part of the file path to replace between locations. lastFileLog is a file used to keep track of the last file that was copied. This is needed to recover from a partial copy. Windows seems to allocate the full file size even when the file fails to copy. So I just keep track of the last file to copy it again on failure. objStartFolder is the starting path on the source network location.
'initialize paths
objStartFolder = "\\owner-pc\d\pics"
lastFileLog = "c:\Files\misc\archive.log"
sourceRoot = "\\owner-pc\d"
targetRoot = "c:\Files"
Set objFSO = CreateObject("Scripting.FileSystemObject")
'read log
Set objFile = objFSO.OpenTextFile(lastFileLog)
Do Until objFile.AtEndOfStream
replacefile= objFile.ReadLine
Wscript.Echo "This file will be replaced: " & replacefile
Loop
objFile.Close
'copy files
Set objFolder = objFSO.GetFolder(objStartFolder)
ShowSubfolders objFSO.GetFolder(objStartFolder)
'clear log
Set objFileLog = objFSO.CreateTextFile(lastFileLog,True)
objFileLog.Write ""
objFileLog.Close
Sub ShowSubFolders(Folder)
For Each Subfolder in Folder.SubFolders
Wscript.Echo Subfolder.Path
if not(objFSO.FolderExists(replace(Subfolder.Path,sourceRoot,targetRoot))) then
objFSO.CreateFolder(replace(Subfolder.Path,sourceRoot,targetRoot))
end if
Set objFolder = objFSO.GetFolder(Subfolder.Path)
Set colFiles = objFolder.Files
For Each objFile in colFiles
if not(objFSO.FileExists(replace(Subfolder.Path & "\" & objFile.Name,sourceRoot,targetRoot))) then
Wscript.Echo Subfolder.Path & "\" & objFile.Name
Set objFileLog = objFSO.CreateTextFile(lastFileLog,True)
objFileLog.Write Subfolder.Path & "\" & objFile.Name
objFileLog.Close
objFSO.CopyFile Subfolder.Path & "\" & objFile.Name, replace(Subfolder.Path & "\" & objFile.Name,sourceRoot,targetRoot)
elseif replacefile = Subfolder.Path & "\" & objFile.Name then
Wscript.Echo "Replacing ... " & Subfolder.Path & "\" & objFile.Name
objFSO.CopyFile Subfolder.Path & "\" & objFile.Name, replace(Subfolder.Path & "\" & objFile.Name,sourceRoot,targetRoot),true
else
Wscript.Echo "Skip ... " & Subfolder.Path & "\" & objFile.Name
end if
Next
ShowSubFolders Subfolder
Next
end sub
For Folder: Try This.
Option Explicit
Dim obj,Itemcoll1,a,b
Set obj=CreateObject("Shell.Application")
Function SelectFold1(Desc)
Set SelectFold1=obj.BrowseForFolder(0,Desc,0,"C:\Users\Mohammed Sajjad\Desktop\")
End Function
Set Itemcoll1=SelectFold1("Copy: ").Items
SelectFold1("Paste: ").CopyHere Itemcoll1 'Use MoveHere if you want to move
MsgBox "Completed"
For File:
Option Explicit
Dim objApp : Set objApp = CreateObject("Shell.Application")
Dim objFSO : Set objFSO = CreateObject("Scripting.FileSystemObject")
Dim objSHL : Set objSHL = CreateObject("WScript.Shell")
'Browse for Folder
'----------------------------------------------------------
Function SelectFold()
Dim objFolder
Set objFolder = objApp.BrowseForFolder(0,"Select a Folder",0,0)
If objFolder Is Nothing Then
MsgBox "Canceled"
WScript.Quit
Else
SelectFold = objFolder.Self.Path & "\"
End If
End Function
'----------------------------------------------------------
'Browse for file
'----------------------------------------------------------
Function SelectFile()
Dim tempFolder : Set tempFolder = objFSO.GetSpecialFolder(2)
Dim tempFile : tempFile = objFSO.GetTempName() & ".hta"
Dim path : path = "HKCU\Volatile Environment\MsgResp"
With tempFolder.CreateTextFile(tempFile)
.Write "<input type=file name=f>" & _
"<script>f.click();(new ActiveXObject('WScript.Shell'))" & _
".RegWrite('HKCU\\Volatile Environment\\MsgResp', f.value);" & _
"close();</script>"
.Close
End With
objSHL.Run tempFolder & "\" & tempFile, 0, True
If objSHL.RegRead(path) = "" Then
objSHL.RegDelete path
objFSO.DeleteFile tempFolder & "\" & tempFile
WScript.Quit
End If
SelectFile = objSHL.RegRead(path)
objSHL.RegDelete path
objFSO.DeleteFile tempFolder & "\" & tempFile
End Function
'----------------------------------------------------------
objFSO.CopyFile SelectFile, SelectFold

vbs read from file and parse it to the batch file

I had a script which worked on win xp but beacuse some of the methods are not available anymore I had to rewrite the script and use mshta.exe.
VBS script should do two things:
Read from file
Parse the info to the batch file
I have done the 1st bit but in the 2nd part I am getting an error. Could you please point me to the right direction?
Option Explicit
Dim objFso
Dim strFileName
Dim strFile
Dim objShell
Dim cimv2
Dim RemoteMachine
Dim YesNo
Dim out
Dim crt
Dim objDialog, intResult
Dim objTextFile, strText, iintresult
Dim objExec, strMSHTA, wshShell
mainMenu
Sub mainMenu()
do
out = inputbox("Choose option:" & vbcr & "1 - Deployment" & vbcr & "0 - Exit", "Menu", "0")
If out="1" then
call SelectFile
End If
If out="0"
then WScript.Quit
End if
loop
End Sub
Sub bgInfo(param)
YesNo = Msgbox("deployment? " & param, 4)
if YesNo = vbYes Then
do while not strMSHTA.AtEndOfStream
RemoteMachine = strMSHTA.ReadLine()
On Error Resume Next
objShell.Run "bginfo.bat " & RemoteMachine, 1, true
On Error Goto 0
loop
end if
End Sub
Sub SelectFile( )
strMSHTA = "mshta.exe ""about:" & "<" & "input type=file id=FILE>" _
& "<" & "script>FILE.click();new ActiveXObject('Scripting.FileSystemObject')" _
& ".GetStandardStream(1).WriteLine(FILE.value);close();resizeTo(0,0);" & "<" & "/script>"""
Set wshShell = CreateObject( "WScript.Shell" )
Set objExec = wshShell.Exec( strMSHTA )
intResult = objExec.StdOut.ReadLine( )
msgbox iintresult
If intResult <> "" Then
call bgInfo(intResult)
End If
Set objExec = Nothing
Set wshShell = Nothing
End Sub
Set objFso = Nothing
Set strFileName = Nothing
Set strFile = Nothing
Set objShell = Nothing
Set cimv2 = Nothing
Set RemoteMachine = Nothing
Set fso = Nothing
I am getting an error in line 33 char 5
Error: Object required: strMSHTA
thank you! :)
I had to add this code:
Set objFso = CreateObject("Scripting.FileSystemObject")
set strFile = objFso.OpenTextFile(param2, 1, True)
Set objShell = WScript.CreateObject("Wscript.Shell")`

Trying to replace a string in a file with values read from a different file in vbscript

I am new to scripting and I cannot figure out how to replace a string in a file with values read from a different file. I have tried storing the values in an array and then plugging them into the replace method but I can't get the loops to work. Here are two of my attempts:
Const ForReading = 1
Const Inc = 0 Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile _
("ReadInFile.txt", ForReading)
Do Until objTextFile.AtEndOfStream
strNextLine = objTextFile.Readline
arrServiceList = Split(strNextLine , ",")
Loop
Set objFS = CreateObject("Scripting.FileSystemObject")
strFile = "OrigFile.txt"
Set objFile = objFS.OpenTextFile(strFile)
Do Until objFile.AtEndOfStream
strLine = objFile.ReadLine
If InStr(strLine,"777")> 0 Then
strLine = Replace(strLine,"777",arrServiceList(Inc)) Inc = Inc + 1;
End If
Loop
Const ForReading = 1
Set fso = CreateObject("Scripting.FileSystemObject")
Set answers = fso.OpenTextFile("OrigFile.txt", ForReading)
Set fdf = fso.OpenTextFile("ReadInFile.txt", ForReading)
Set computers = CreateObject("Scripting.Dictionary")
Do Until answers.AtEndOfStream Or fdf.AtEndOfStream
computers.Add names.ReadLine, locations.ReadLine
Loop
names.Close
locations.Close
I also tried a for each loop to read the array but I cannot incorporate it with the other loop.
I did some rebuilding with comment to help you on your way. Please try to understand each step.
Option Explicit ' this makes sure you don't forget to declare variables
Const ForReading = 1
Dim objFSO, objTextFile
Dim serviceCollection, service, strNextLine
Dim i ' i is a variable, it get incremented. So don't make it a const
Dim strLine, objReadFile, objWriteFile
Set objFSO = CreateObject("Scripting.FileSystemObject")
' An ArrayList let you .Add items to the collection without redimming it like a
' native array
Set serviceCollection = CreateObject("System.Collections.ArrayList")
Set objTextFile = objFSO.OpenTextFile("ReadInFile.txt", ForReading)
Do Until objTextFile.AtEndOfStream ' Reads an textfile from start to end
strNextLine = objTextFile.Readline
for each service in Split(strNextLine , ",") ' This splits a single line into parts on the comma character
serviceCollection.Add service
Next
Loop
' Make an array from all services
arrServiceList = serviceCollection.ToArray()
Set objReadFile = objFSO.OpenTextFile("OrigFile.txt")
Set objWriteFile = objFSO.CreateTextFile("NewFile.txt", true)
i = 0
Do Until objReadFile.AtEndOfStream
strLine = objReadFile.ReadLine
If InStr(strLine,"777")> 0 Then
' This next line is not totally safe, because arrServiceList can go over its upperbound
strLine = Replace(strLine, "777", arrServiceList(i))
i = i + 1;
End If
' Important! Write the line to the new textfile
objWriteFile.WriteLine strLine
Loop
' It is good practice to close opened files
objReadFile.Close
objWriteFile.Close
Still you can get some issues: When there are multiple 777s on one line, they get replaced with the same variable because i is not incremented in the mean time. You could solve this by replacing it with something like
Do Until objReadFile.AtEndOfStream
strLine = objReadFile.ReadLine
do
If InStr(strLine,"777")> 0 Then
strLine = Replace(strLine, "777", arrServiceList(i), 1, 1)
i = i + 1;
thereWasAReplace = True ' do not forget to declare
else
thereWasAReplace = False
End If
Loop While thereWasAReplace
' Write the line to the new textfile
objWriteFile.WriteLine strLine
Loop
Disclaimer: I did this from the top of my head, so you can encounter a little bug or two.

How to make a batch file edit a text file

I got the code
Set objFS = CreateObject("Scripting.FileSystemObject")
strFile = "C:\test\file.txt"
Set objFile = objFS.OpenTextFile(strFile)
Do Until objFile.AtEndOfStream
strLine = objFile.ReadLine
If InStr(strLine,"ex3")> 0 Then
strLine = Replace(strLine,"ex3","ex5")
End If
WScript.Echo strLine
Loop
The strLine replacing part i can fix myself to use with my own purposes, but how do i do something like this so that it doesn't require the file's name, it just edits all text files within the document?
you can do it like this,
strFolder = "c:\myfolder"
Set objFolder = objFS.GetFolder(strFolder)
For Each strFile In objFolder.Files
strFileName =strFile.Name
strFilePath = strFile.Path
strFileExt = objFS.GetExtensionName(strFile)
If strFileExt = "txt" Then
Set objFile = objFS.OpenTextFile(strFile)
' your current code here..
objFile.Close()
End If
Next

Resources